Home > Back-end >  Redux - update a value in an array of objects
Redux - update a value in an array of objects

Time:09-28

I would like to update a property from my array onClick. How could I access a specific note, knowing that I already mapped through the array to display it? I would like to modify "description" on click.

My data:

export const NOTES = [
  {
    description: "My description",
    id: 0,
  },
  {
    description: "My description",
    id: 1,
  }
]

My reducer:

import { NOTES } from '../../../../shared/spec-ressources/notes'

const INITIAL_STATE: any[] = [...NOTES];

export const reducer = (state: any[] = INITIAL_STATE, action: any) => {
  switch (action.type) {
    default:
      return state;
  }
}


export default reducer;

CodePudding user response:

first, you need a proper action name, for example, we produce an update action and delete action to work with your data:

in your action file:

const UPDATE_DESCRIPTION = "UPDATE_DESCRIPTION";
const DELETE_DESCRIPTION = "DELETE_DESCRIPTION";

const updateDescription = (newData) => ({type: UPDATE_DESCRIPTION, payload: newData)}

const deleteDescription = (id) => ({type: DELETE_DESCRIPTION, payload: id})

now import actions name into your reducer and import the action method in your component/view/pages to trigger an action.

in reducer:

import { NOTES } from '../../../../shared/spec-ressources/notes'
import {UPDATE_DESCRIPTION ,DELETE_DESCRIPTION } from 'actions'; // --> add your action path here

const INITIAL_STATE: any[] = [...NOTES];

export const reducer = (state: any[] = INITIAL_STATE, action: any) => {
  switch (action.type) {
    case(UPDATE_DESCRIPTION):
      return {
        ...state,
        notes: state.notes.map(note => note.id === action.payload.id ? {
            ...note,
            description: action.payload.newDescription
          } : note)
    }
    case (DELETE_DESCRIPTION):
      return{
        ...state,
        notes: satet.notes.filter(note => note.id !== action.payload.id)
      }
    default:
      return state;
  }
}


export default reducer;

Note 1: your new data about your post should contain an id and description which id is your desire post to update and the description is a new description (updated one) that arrived via dispatching action via updateDescription method.

Note 2: this is the basic and pure implementation for your redux/action/reducer and you can custom it using differents redux helpers libraries but the structure is the same.

CodePudding user response:

  switch (action.type) {
    default:
      return {
      ...state,
      NOTES:  state.NOTES.map(note=> note.id === 1 ? {...note, description: 'some description'}: {...note})
   }
  }
  • Related