Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How i can change UI on change redux-toolkit state?

I want to rerender my component when i’m dispatch from another component, how i can do it?

Component that need for rerender:

const MessageComponent = (): JSX.Element => {
    const [messages, setMessages] = useState<IMessageComponentState>({
        messages: []
    })

    const message = useSelector((state: RootState) => state.message.messages);

    useEffect(() => {
        setMessages({
            messages: message
        })
        console.log(message)
    }, message);



    return (
        <>
            {messages.messages}
            <MyMessageComponent  message="some text"/>
            <IncomeMessageComponent  message="some text2"/>
        </>

    )
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Dependency in useEffect have to put inside [ ]. See more: Conditionally firing an effect.

And messages state is an array but you set a object, change from setMessages({ messages: message }) to setMessages((mes) => [...mes, {messages: message}])

const MessageComponent = (): JSX.Element => {
    const [messages, setMessages] = useState<IMessageComponentState>({
        messages: []
    })

    const message = useSelector((state: RootState) => state.message.messages);

    useEffect(() => {
        setMessages((mes) => [...mes, {
            messages: message
        }])
        console.log(message)
    }, [message]); //<=== Put message in []



    return (
        <>
            {messages.messages}
            <MyMessageComponent  message="some text"/>
            <IncomeMessageComponent  message="some text2"/>
        </>

    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading