Patrik Rikama-Hinnenberg
Patrik Rikama-Hinnenberg

Reputation: 1600

Update object value in array React hooks way

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.

Upvotes: 0

Views: 3628

Answers (3)

Ericgit
Ericgit

Reputation: 7063

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!

Upvotes: 0

Dupocas
Dupocas

Reputation: 21317

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

Upvotes: 3

Ori Drori
Ori Drori

Reputation: 191976

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

Upvotes: 2

Related Questions