Patrik Rikama-Hinnenberg
Patrik Rikama-Hinnenberg

Reputation: 1600

Push a new value to nested array in React hooks

I have a function onTagSelected() that updates now a single value for a key inside a object:

const NotesContainer = ({

}) => {
  const [notesDummyData, setNotesDummyData] = useState([
    {
      id: '5',
      title: 'Sauna',
      tag: 'relax',
    },
    {
      id: '7',
      title: 'Finland',
      tag: 'nordics'
    },
  ]);

    const onTagSelected = (selectedTag, itemId) => {
     setNotesDummyData(notesDummyData.map((x) => {
       if (x.id !== itemId) return x;
       return { ...x, tag: selectedTag };
     }));
   };

Now I would like to change the function and be able to take many tags. How should I go about modify the function to push new tag values to the new nested tag: array.

    const [notesDummyData, setNotesDummyData] = useState([
    {
      id: '5',
      title: 'Sauna',
      tag: ['relax', 'wellness']
    },
    {
      id: '7',
      title: 'Finland',
      tag: ['nordics', 'winter']
    },
  ]);


    const onTagSelected = (selectedTag, itemId) => {

    // Push new tag to nested array for specific item -> tag: ['nordics', 'winter', 'selectedTag']

  };

Upvotes: 1

Views: 2177

Answers (2)

Sanatan Chaudhary
Sanatan Chaudhary

Reputation: 404

You can use es6 destructuring to add new items to an array.

  const onTagSelected = (selectedTag, itemId) => {
     setNotesDummyData(notesDummyData.map((x) => {
       if (x.id !== itemId) return x;
       return { ...x, tag: [...x.tag, selectedTag] };
     }));
  }

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

spread the previous tag and add selectedTag to end

just change this

return { ...x, tag: selectedTag };

to

return { ...x, tag: [...x.tag, selectedTag] };

Or

return { ...x, tag: x.tag.concat(selectedTag) };

Upvotes: 5

Related Questions