Search code examples
reactjsreact-nativereact-hookssetstate

how to set state array using react hooks


Thanks in advance. I have a state array as below.

I need to add an item to state array, I came across that we need not do state mutation. How do i set state with prevState.

const [messages, setMessages] = React.useState(
        [
            {
                _id: 12,
                createdAt: new Date(),
                text: 'All good',
                user: {
                    _id: 1,
                    name: 'Sian Pol',
                }
            },
            {
                _id: 21,
                createdAt: "2019-11-10 22:21",
                text: 'Hello user',
                user: {
                    _id: 2,
                    name: 'User New'
                }
            }]
    )

How to to i call the set State to append this state array.

Something like this?

setMessages(previousState => ({...stat

Can anyone help me in getting the above line code.


Solution

  • To insert new element at the end of the list

    const addMessage = (newMessage) => setMessages(oldMessages => [...oldMessages, newMessage])
    

    To insert new element at the begining of the list

    const addMessage = (newMessage) => setMessages(oldMessages => [newMessage, ...oldMessages])