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

Issue

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"/>
        </>

    )
}

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"/>
        </>

    )
}

Answered By – VMT

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published