Home > Enterprise >  Update state using array.find for redux return reference or value?
Update state using array.find for redux return reference or value?

Time:12-17

I am following the tutorial on the official website.

I know that the state is immutable and the operation in reducer is actually create a new copy of the state, modify it and replace the original one.

I am thinking: isn't it suppose to delete the entry(exisitngPost) in the array and push a new one in instead? As state.find() should return by value instead of reference. Do I get it wrong? or it is something to do with reducer logic?

tutorial link

const postsSlice = createSlice({
  name: 'posts',
  initialState,
  reducers: {
    postAdded(state, action) {
      state.push(action.payload)
    },
    postUpdated(state, action) {
      const { id, title, content } = action.payload
      // where i find confused<<<<<<<<<<<<<<<<<<<
      const existingPost = state.find(post => post.id === id)
      if (existingPost) {
        existingPost.title = title
        existingPost.content = content
      }
    }
  }
})

export const { postAdded, postUpdated } = postsSlice.actions

export default postsSlice.reducer

CodePudding user response:

state.find returns the object in state there - and if it is not a primitive, that object will be a reference. So at that point in a RTK immer reducer you can modify it and after the reducer is run, a new immutable copy with the applied changes will be created for you instead of modifying the original.

  • Related