Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

243
Visualizações
how to change value of object in array using setState with React

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 :)

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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!

about 4 years ago · Santiago Trujillo Relatório

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda