An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
January 20, 2021 05:27 pm GMT
Original Link: https://dev.to/raphaelchaula/how-to-update-object-or-array-state-in-react-4cma
How to update object or array state in React
Ever tried to update object or array state directly in React?
I did that, the state of my component didn't change.
Destructuring the object/array was the solution.
When you update the state, create a new array/object by destructuring the one in the state, manipulate it then set it as a new value in the state.
Object
import React, { useState } from 'react';const States = () => { const [objectValue, setObjectValue] = useState({}); const updateObjectValue = (key, value) => { // Destructure current state object const objectvalue = { ...objectValue, [key]: value, }; setObjectValue(objectvalue); }; return <Component/>;};export default States;
Enter fullscreen mode Exit fullscreen mode
Array
import React, { useState } from 'react';const States = () => { const [arrayValue, setArrayValue] = useState([]); const updateArrayValue = (value) => { // Destructure current state array const arrayvalue = [ ...arrayValue ]; arrayValue.push(value); setArrayValue(arrayvalue); }; return <Component/>;};export default States;
Enter fullscreen mode Exit fullscreen mode
Happy Hacking!
Original Link: https://dev.to/raphaelchaula/how-to-update-object-or-array-state-in-react-4cma
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To