0

I'm trying to change input values in the object with one action. so the action gets key("title" and "content") value as a parameter from each input when its type. It filler the note array object id match with activeId. Assign value const noteValue = { [action.key]: action.value }; when I console.log it shows the object with correct value however, I can't return the correct value with spread operator. I tried with map but it returns boolean. so I don't think it is the correct approach. It would be very helpful with guidance. Thank you.

component

<div key={id}>
  <Title
   type="text"
   defaultValue={title}
   onChange={e => editNote("title", e.target.value)}
  ></Title>
  <NoteContent
    type="text"
    defaultValue={content}
    onChange={e => editNote("content", e.target.value)}
  ></NoteContent>
</div>

action

export const editNote = (key, value) => ({
  type: EDIT_NOTE,
  key,
  value
});

state

const initialState = {
  notes: [
    {
      id: "1234",
      title: "title 1",
      content: "content 1"
    },
    {
      id: "5678",
      title: "title 2",
      content: "content 2"
    },
    {
      id: "9101112",
      title: "title 3",
      content: "content 3"
    }
  ],
  activeId: null
};

reducer

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case SET_ACTIVE_ID:
      return { ...state, activeId: action.activeId };
    case EDIT_NOTE:
      const note = state.notes.filter(note => note === state.activeId);
      const noteValue = { [action.key]: action.value };
      const noteArr = [...note, { ...noteValue }];
      console.log(noteArr);
      return { ...state, notes: [...state.notes, ...noteArr] };

    default:
      return state;
  }
}
MachoBoy
  • 161
  • 4
  • 15

1 Answers1

0

you can use map and try like below

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case SET_ACTIVE_ID:
      return { ...state, activeId: action.activeId };
    case EDIT_NOTE:
      const updatedReuslt = state.notes.map((note)=>{
        if(note.id === state.activeId){
          return {...note, [action.key] : action.value }
        } else {
          return note;
        }
      })
      return { ...state, notes:updatedResult };

    default:
      return state;
  }
}
sathish kumar
  • 1,477
  • 1
  • 11
  • 18
  • Thank you @sathish kumar. Your approach worked so well except there was a typo `const updateReuslt`. oh, man.. it was easier than I thought. Thank you again. – MachoBoy Jan 29 '20 at 08:27