Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 20, 2021 05:27 pm GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To