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

127
Visualizações
ReactJS Add to Object that is a State

hoping this is a simple answer but it's racking my brain. Let's say I have the following React pseudocode:

const [cats, setCats] = useState({});

console.log(cats);

cats = {

}

I am trying to add uh cats to the cats object via a button click. I'm not sure what the exact code should be, as any guess I have so far doesn't work. The closest i've gotten is the following pseudo code:

heres the object i'm sending in:

{
Bruto:{
     id : 2,
     name: 'Bruto',
     }
}

const addCat (e, catName) => {
setCats(...cats, event.target.value);
}

<input onKeyDown={e=>addCat(e,catDetails)}></input>

Which all it does is just add the word typed into the input as cats, but doesn't add it structurally. Ideally what i'd want is the following:

1. Check to see if catDetails exists in cats
2. If not, add the catDetails.id to the object 
3. Add catDetails.name to cats[catDetails.id] such as the object should be:
    cats{
       0: {
         name: "Heathcliff"
        }
       2: {
         name: "Bruto"
        }
      }

Hoping someone can help. Below is the code I have so far

const addTag = (event, cats) => {
    if (event.key === "Enter"){
     setCats(...cats, event.target.value)
    }
   console.log(cats);
  }

Thank you!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can do:

setCats( prevCats => {...prevCats, {id:2, name:"Bruto"});

Or if you want the IDs as keys:

setCats( prevCats => {...prevCats, [id]: name});

Instead of passing the new state to setCats you pass a function which will automatically receive the previous state, and whatever is returned will be used as the new state.

Or even better: you can use useReducer instead of useState

about 4 years ago · Juan Pablo Isaza Relatório

0

You'll probably find an array easier to use.

Have one state (an array) for all your cat objects, and have another (string) for the cat you're adding in the input, and then update the cats array with the current cat if it's not been found.

const { useEffect, useState } = React;

function Example() {

  // Initialise cat states
  const [ cats, setCats ] = useState([]);
  const [currentCat, setCurrentCat] = useState('');

  // Updates the currentCat state when the input changes
  function handleChange(e) {
    setCurrentCat(e.target.value);
  }

  // First find out if the cat name we're entering exists
  // in the cats array. If it doesn't, add it
  function addCat(e) {
    const found = cats.find(cat => cat.name === currentCat);
    if (!found) {
      setCats([
        ...cats,
        { id: cats.length  + 1, name: currentCat }
      ]);
    }
  }

  useEffect(() => console.log(cats), [cats]);

  return (
    <div>
      <input
        type="text"
        onChange={handleChange}
       />
      <button
        type="button"
        onClick={addCat}
      >Add cat
      </button>
    </div>
  );
};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza 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