paul blackmore
paul blackmore

Reputation: 331

Replacing object for another in state React

I have an array of objects. I find the object I need to replace but can't replace it in state. The original object stays untouched and the object I want to replace it with is added to the end of the array. I'm use React hooks. Thanks

case types.ADD_USERNAME: 
  let task = action.payload
  let assignedTask = state.tasks.find(el => el.id === task.id)
  let index = state.tasks.indexOf(assignedTask)

  return {
    ...state, 
    tasks: [
      ...state.tasks,
      assignedTask = {
        ...assignedTask,
        user: task.user.name
      }
    ]
} 

Upvotes: 2

Views: 560

Answers (2)

Clarity
Clarity

Reputation: 10873

You could achieve this by using map and matching your object by id or any other unique identifier:

case types.ADD_USERNAME:
  let task = action.payload;

  return {
    ...state,
    tasks: state.tasks.map(t => {
      if (t.id === task.id) {
        return {
          ...t,
          user: task.user.name
        };
      }
      return t;
    })
  };

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 282040

You can make use of map instead of going by index and find element to update the state which in my opinion is a cleaner approach

case types.ADD_USERNAME: 
  let task = action.payload;

  return {
    ...state, 
    tasks: state.tasks.map(el => {
        if(el.id == task.id) {
           return { ...el, user: task.user.name} 
        }
        return el;
    });
} 

However if you wish to go by the index and find element approach, you need to slice the task array and update the specific index element

case types.ADD_USERNAME: 
  let task = action.payload
  let index= state.tasks.findIndex(el => el.id === task.id);

  return {
    ...state, 
    tasks: [
      ...state.tasks.slice(0, index - 1),
      {
        ...state.tasks[index],
        user: task.user.name
      }
      ...state.tasks.slice(index + 1)
    ]
} 

Upvotes: 2

Related Questions