Chiara Perino
Chiara Perino

Reputation: 920

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"??

Upvotes: 1

Views: 720

Answers (2)

Chiara Perino
Chiara Perino

Reputation: 920

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 } };

Upvotes: 1

ddavydov
ddavydov

Reputation: 76

Here is an example that can work for your case:

import { persistCombineReducers, persistReducer } from 'redux-persist';

const draftPersistConfig = { key: 'draft', storage: AsyncStorage };

const reducers = { products: persistReducer(draftPersistConfig, products), // ...other reducers if you have any }

const persistConfig = { key: 'root', storage: AsyncStorage, debug: true, whitelist: ['draft'] };

persistCombineReducers(persistConfig, reducers); should return you rootReducer that you can use to create store

Upvotes: 0

Related Questions