I have a functional react component which receives a random message object regularly. It displays the new added item properly. After I delete one item and received a new message, deleted item remains again. I solved by using Object.assign(), but not sure why spread operator is not working.
I think spread operator copies array. I have been using spread operator when adding new item to array state variable. When to use Object.assign(), when to use spread operator?
Here is my code.
const myComp = props => {
const [messages, setMessages] = useState([]);
const [api] = useState(new Api({
messageCallback: (msg) => {
handleCallback(msg);
},
}));
useEffect(()=>{
api.start();
},[])
const handleCallback = msg => {
messages.push(msg);
setMessages([...messages]);
}
const deleteItem = index => {
messages.splice(index,1);
setMessages([...messages]);
}
return (
<div>
{
messages.map((item, index)=>(
<p key={index} onClick={(e)=>deleteItem(index)}>{item.message}</p>
))
}
</div>
)
}
This works not properly so I solved by using this.
const handleCallback = msg => {
const temp = Object.assign(messages,[]);
temp.push(msg);
setMessages(temp)
}
In general, many developers are adding a new item by the DOM event. In my app, it is automatically added by the API without rendering the UI. That was the problem. https://thecodebarbarian.com/object-assign-vs-object-spread.html
Spread operator also copies the array but have different value though original value changes. When you use Object.assign, copied value has the same value when original value changes.
In my app, when I use spread operator, message variable remains the original empty value though it seems to change.
Top comments (0)