Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
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!

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading