Home > other >  Uncaught Error: [Immer] An immer producer returned a new value *and* modified its draft. Either retu
Uncaught Error: [Immer] An immer producer returned a new value *and* modified its draft. Either retu

Time:10-03

Im using redux-toolkit and i'm trying to update an array of posts such that when the user clicks the remove button it sends the post object (which has {id, description, imageLink}, to the reducer and removes that object from the state array, returning the updated array.

I have this button that calls the dispatch method on click

<button className='remove-button' onClick={() => dispatch(removePost(post))}>Remove</button>

The format of the post looks like this

{id: 1, description: 'some-description', imageLink: 'some-link.jpg'}

here is the state array

posts = [
  {
    id: 0,
    description: "A-description",
    imageLink:  "a-link.jpg",
  },
  {
    id: 1,
    description: "some-description",
    imageLink: "some-link.jpg",
  },
  {
    id: 2,
    description: "another-description",
    imageLink: "another-link.jpg",
  }
]

and finally here is the code in my reducer

export const postSlice = createSlice({
  name: "posts",
  initialState: MyPosts,
  reducers: {
    removePost: (state, action) => {
      console.log(action.payload);
  

     for(var i = 0; i < state.length; i  ){
        if(JSON.stringify(state[i]) == JSON.stringify(action.payload)){
        
            return [...state.splice(i, 1)]
        
        }
     }
  
    },
    addPost: (state, action) => {
      console.log(action.payload);

      return [...state, action.payload];
    },
  },
 });

the addPost reducer works fine but for some reason I cannot remove a post

CodePudding user response:

Ok, I see my other provided answer solved the problem with the immer error, but still is insuficient.

You probably want something like this:

removePost: (state, action) => state.filter(i => JSON.stringify(state[i]) != JSON.stringify(action.payload)); 

CodePudding user response:

On line

return [...state.splice(i, 1)]

you are returning the new state. But also, you are changing the current state with the splice method call. Use slice instead, because that way your removePost method wont change the state variable, it will only return the new state.

The code should be

return [...state.slice(i, 1)]
  • Related