0

How would I update a title of the specific id with hooks state setup. Here:

const NotesContainer = ({

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

  const onChangeItemName = (newTitle, oldTitle, itemId) => {

    //Update a new title here for id 7

  };

Could not find any example for setState hooks.

3 Answers 3

3

Just map through the items and if the id is equal to the selected id you modify only the value:

 const onChangeItemName = (newTitle, oldTitle, itemId) => {
      setNotesDummyData(notesDummyData.map(x => {
           if(x.id !== itemId) return x
           return {...x, title: newTitle}
      }))
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Sweet, this made it happen.
Great! Consider accepting one of the answers to close the question
Love the approach of first returning all non matches. The stripped down "if else" is clean and raw, getting use to it now :) added ; after the returns ' return x; ' and ' return {..x, title: newTitle}; '
2

You can use Array.map(). For each item check if the id is equal to itemId. If it this, spread the item, and replace the title. If not, return the original item:

const onChangeItemName = (title, itemId) => {
  setNotesDummyData(notesDummyData.map(o => o.id === itemId ? ({
    ...o,
    title
  }) : o));
};

Comments

0

It's easy to update data using React Hook, but there is not working setState(), so there will be working [notThis, thisOne(setNotesDummyDate)] to update your data.

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

Using React Hook method to Update data:

const onChangeItemName = (newTitle, oldTitle, itemId) => {
       setNotesDummyDate = useState([
    {
      id: itemId, // Update
      title: newTitle,
    },
    {
      id: itemId, // Update
      title: newTitle,
    },
  ]);
 }

Still Curious, study here about useState()

Cheer you!

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.