Search code examples
react-nativereduxredux-persist

React-Native Persist object of objects with redux-persist


I have this state in redux:

draft: {
    temporary: { clientId: null, shoppingCart: [] },
},

in my shoppingCart, I push some objects with react-addons-update:

const newState = { ...state };
let cart = newState.draft.temporary.shoppingCart;
cart = update(cart, { $push: [{ id: 1, quantity: 3 }] });
newState.draft.temporary.shoppingCart = cart;
return newState;

and my newState in the app is:

draft: {
        temporary: { clientId: null, shoppingCart: [
            {id: 1, qnt: 3},
        ]},
    },

I config my products reducer with:

products: persistReducer(products: {
    key: 'products',
    storage,
    whitelist: ['draft'],   
}, products),

but my store isn't persisted once the application is reloaded.

UPDATE:

example solution that works:

newState.draft = { ...newState.draft, temporary: { ...newState.draft.temporary, shoppingCart: [ ...newState.draft.temporary.shoppingCart, { id: 1, qnt: 3 } ]}};

solution without react-addons-update that doesn't work:

newState.draft.temporary.shoppingCart = [ ...newState.draft.temporary.shoppingCart, { id: payload.id, quantity: 1 } ];

There is a "cleaner solution"??


Solution

  • The final solution that I have used was changing reducer:

      const newDraft = { ...state.draft };
      let cart = state.draft.temporary.shoppingCart;
    
      const index = _.findIndex(cart, { id: payload.id });
    
      if (index === -1) cart = update(cart, { $push: [{ id: payload.id, quantity: 1 }] });
      else cart = update(cart, { [index]: { quantity: { $set: cart[index].quantity + 1 } } });
    
      newDraft.temporary.shoppingCart = cart;
    
      return { ...state, draft: { ...newDraft } };