• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

81
Views
How to update just one object from a list of objects in Redux by id?

I build an app in React with Redux and in my state I have a list of objects and I want to update one object from that list by unique id.

My object looks like:

{
id: '',
title: '',
description: '',
label: '',
}

My state:

const initialState = {
    compare: dayjs().month(),
    savedEvents: [],
}

When I push a new event in that list I use:

case 'events/setNewEvent':
            return { ...state, savedEvents: [...state.savedEvents, action.payload] };

My problem is that I don't know to write the right code to update just one object by id sent from my form.

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use combination of Array method map and spread operator

function updateOne(array, obj) {
  return array.map((item) => {
    if (obj.id === item.id) {
    // update whatever you want
    return {...item, title: obj.title };
   } else {
    return item;
   }
 })
}

reducer:

case 'events/setNewEvent':
   return { 
    ...state, 
    savedEvents: updateOne(state.savedEvents, action.payload) 
  };

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error