Home > Software engineering >  how to change value of object in array using setState with React
how to change value of object in array using setState with React

Time:12-27

hello everyone good evening,

I have array of object set in state and i would like to change some object in the array.

so here is my array us you can see:

    const [CategoriesArr, setCategoriesArr] = useState([
    {
        image: anime,
        nameByCategories: "Aninate",
        allCard: [
            silverCard, blackCard
        ],
    },
    {
        image: vacation,
        nameByCategories: "Vacation",
        allCard: [
            blackCard, silverCard
        ],
    },])

i tried to change the allCard to: allCard:blackCard, blackCard

with this way:

setCategoriesArr([
{
    ...CategoriesArr[0],
    allCard: [
        silverCard, silverCard
    ]
}])

the problem is after the setState i get new array with changes that i want and also the last array so it means like this

  {
        image: anime,
        nameByCategories: "Aninate",
        allCard: [
            blackCard, blackCard
        ],
    },
    {
        image: vacation,
        nameByCategories: "Aninate",
        allCard: [
            silverCard, blackCard
        ],
    },
  {
        image: anime,
        nameByCategories: "vacations",
        allCard: [
            blackCard, silverCard
        ],
    },

i would like to understand i can i get new array exact like that:

    const [CategoriesArr, setCategoriesArr] = useState([
{
    image: anime,
    nameByCategories: "Aninate",
    allCard: [
        silverCard, blackCard
    ],
},
{
    image: vacation,
    nameByCategories: "Vacation",
    allCard: [
        blackCard, blackCard
    ],
},])

pleas.

i hope you guys going to help me :)

CodePudding user response:

The issue is setter method (from useState hook) is not like setState in class components that merge the changes to the existing state.

By using the callback function of the setter gives you the previousState to merge the new changes to and return (in your case change is only a property of the first item in the state).

This one would also work.

   setCategoriesArr((prevValue) => {
      return prevValue.map((item, itemIndex) => {
        if (itemIndex === 0) {
          return { ...item, allCard: ["silverCard", "silverCard"] };
        } else {
          return item;
        }
      });
    });

Code sandbox => https://codesandbox.io/s/runtime-shadow-2bbxh?file=/src/App.js

CodePudding user response:

There is a simple way to do it.

const updateCategoryList = (id) => {
  const newCategories = CategoriesArr.map(cate => {
    if (cate.nameByCategories === id) { // <= id can be "Aninate" or anything you want
      cate.allCard[silverCard, silverCard]
      return cate;
    }
  })
  setCategoriesArr(newCategories)
}

you can use this updateCategory function with event handler or with other functions or components you want.

I hope you find a solution!

  • Related