I'm starting with React and I need to use the 'useState()' function in a site.
First, I'm creating the useState variable:
const [messages, setMessages] = useState(['1111', '222'])
Then I'm returning a div with the messages.
Up to here it's working, but I have to use my 'SetMessages' command:
setMessages(...messages, '333')
And when I write it , my site it stops working and all I see is a white page. I've seen many videos about it and I literraly copied pasted their codes them and it still didn't work, what's wrong with my code and how to use this second command from 'useState' right?
CodePudding user response:
When using the spread operator (...) you still need to to wrap that in an object or an array. So [...x, y] or {...x, y}.
In your case
setMessages([...messages, '333'])
CodePudding user response:
Use this
setMessages(prevMsgs=>[...prevMsgs,"333"])