Marcin Szaro
Marcin Szaro

Reputation: 49

Error while updating redux state using immutability-helper

I'm trying to set one exact value, stored in array which is stored in my state object, all in redux.

const initialState = {
    orderedItems: [
    {item:"1Reco",price:"12",amount:1},
    {item:"2Reco",price:"12",amount:1},
    ],
    fullPrice: 0,
    windowWidth: 1418,
    language: "en"
};

Let's say 2Reco amount to 2. I have been trying to use update and $set like that:

let newamount = state.orderedItems[i].amount+1;
return update(state, { 
    orderedItems: { 
        [i]: {
            amount: {$set:newamount}
      }
    },fullPrice: newPrice
  });

But when this update is firing,im getting "Error: update(): You provided an invalid spec to update()." back, and I don't know why. I have seen simillar solutions here on stack earlier, and they don't seem to work for me. When console logging, newamount shows a number 2, so exactly what I want to set in that place. What is the problem?

Upvotes: 0

Views: 284

Answers (2)

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8098

You are mutating the state directly. In a general scenario in Redux you must ... operator. Something like this:

For

orderedItems: [
  {item:"1Reco",price:"12",amount:1},
  {item:"2Reco",price:"12",amount:1},
],

Try

const updatedOrderedItems = orderedItems.map(obj=>{
                if(obj.item==="2Reco"){
                    obj.amount=obj.amount+1;
                    return obj; 
                }
                return obj;
});

Now your updatedOrderedItems contains the updated array of object containing the amount 2 for second object.

Then you can update global state in redux from your reducer function as follows:

return{
  ...state,
    orderedItems: updatedOrderedItems 
    fullPrice: 0,
    windowWidth: 1418,
    language: "en"
   
}

Upvotes: 0

markerikson
markerikson

Reputation: 67469

While it's not a directly answer to your question, I would strongly recommend using Immer to write immutable updates instead of the immutability-helper library:

https://immerjs.github.io/immer/docs/introduction

The code will be much simpler.

In addition, our official Redux Toolkit package already uses Immer internally, and you should be using Redux Toolkit to write your Redux logic.

Upvotes: 1

Related Questions