IntoTheDeep
IntoTheDeep

Reputation: 4118

Redux manipulate state object

My target is to add element of mapped array into redux object. Example: List of Students json

[
    {id: "1", name: "Anie"},
    {id: "2", name: "John"}
]

In Redux I have:

const initialState = {
  students: []
}
const students = (state = initialState, action) => {
  switch (action.type) {
    case 'ALL_STUDENTS':
      return Object.assign({}, state, {
        students: action.students
      })
    }
}

My target is data to look like that:

[
    {someprop: "", student: {id: "1", name: "Anie"}},
    {someprop: "", student: {id: "2", name: "John"}}
]

I need add user object as a prop of person object in Object assign. How is that possible. Which is most correct way to do that?

Upvotes: 1

Views: 132

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122155

You can use map() method on passed list of students to add new property to each object inside and then use spread syntax in object and array to add those new properties.

const initialState = {
  students: []
}
const students = (state = initialState, action) => {
  switch (action.type) {
    case 'ALL_STUDENTS':
      return {
        ...state,
        students: [...action.payload.map(student => {
          return {someprop: '', student}
        })]
      }
          
    default:
      return state;
  }
}

var newStudents = {
  type: 'ALL_STUDENTS',
  payload: [{id: "1", name: "Anie"},{id: "2", name: "John"}]
}

let state = students(undefined, newStudents);
console.log(state)

Upvotes: 3

Related Questions