how to set state array using react hooks

Ankit Jayaprakash picture Ankit Jayaprakash · Nov 29, 2019 · Viewed 19.1k times · Source

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.

Answer

tolotra picture tolotra · Nov 29, 2019

To insert new element at the end of the list

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

To insert new element at the begining of the list

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