0

I am wondering how do I push an object to an array that is located inside to another array, using useState. below is my code:

import React, {useState} from 'react';

const Context = React.createContext();

export const Provider = ({children}) =>{

  const [categories, setCategory] = useState([
    { title: 'Personal' , id: Math.floor(Math.random()* 99999), notes: [
      { noteTitle: 'stam', 
        noteContent: 'stamstamstam',
        id: Math.floor(Math.random()* 99999)
      },
      { noteTitle: 'stam2',
        noteContent: 'stamstamstam232323',
        id: Math.floor(Math.random()* 99999)
      }
    ]},
    { title: 'Work' , id: Math.floor(Math.random()* 99999), notes: []},
    { title: 'Shopping' , id: Math.floor(Math.random()* 99999), notes: []}
  ]);

  const addNoteForCategory = (name, content, categoryId) => {
    const chosenCategory = categories.find((category) => category.id === categoryId)  
    setCategory([...chosenCategory.notes, {
      noteTitle: name, 
      noteContent: content, 
      id: Math.floor(Math.random()* 99999)
    }])
  }

}

2 Answers 2

2

You could use map and change the item you want to change, then update the state.

const updatedCategories = categories.map(category => {
    if (category.id === 123) {
        return {
            ...category,
            notes: [
                ...category.notes,
                { title: 'Note 2' }
            ]
        }
    }

    return category;
});

setCategory(updatedCategories);

You need to replace the dummy ids and data that I used with your specific data.

Sign up to request clarification or add additional context in comments.

Comments

0
const addNoteForCategory = (name, content, categoryId) => {
      setCategory( prevState => {
        const chosenCategory = prevState.find((category) => category.id === categoryId);
        chosenCategory.notes.push({
          noteTitle: name, 
          noteContent: content, 
          id: Math.floor(Math.random()* 99999)
        });
        return prevState
    });

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.