1

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']

  };

2 Answers 2

5

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) };
Sign up to request clarification or add additional context in comments.

Comments

1

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] };
     }));
  }

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.