bjoluc / next-redux-cookie-wrapper

Sync a subset of your Redux state with cookies in Next.js :cookie: :sparkles:
MIT License
114 stars 4 forks source link

Properties removed if not included in subtrees. #19

Closed LucasLundJensen closed 3 years ago

LucasLundJensen commented 3 years ago

Hi,

I've run into the scenario that I want to save part of my state in the cookies, but don't care about the rest. My state "cart" contains PRODUCTS, ITEMS and TOTAL and I only want to "persist" ITEMS.

My issue now is that the PRODUCTS and TOTAL properties get removed competely on HYDRATE, as shown in the image here: Image of State

This is my code:

const rootReducer = (state, action) => {
    switch (action.type) {
        case HYDRATE:
            return {
                ...state,
                ...action.payload
            }
        default:
            return combinedReducers(state, action);
    }
};

const makeStore = wrapMakeStore(() =>
    createStore(
        rootReducer,
        composeWithDevTools(
            applyMiddleware(
                nextReduxCookieMiddleware({
                    subtrees: ["cart.ITEMS"],
                    maxAge: 1209600000
                }),
                thunkMiddleware
            )
        )
    )
);

Is this just me not implementing proper state reconciliation? If it is, could you provide an example?

bjoluc commented 3 years ago

Hi @LucasLundJensen,

Is this just me not implementing proper state reconciliation?

that seems to be the case. Internally, only those state paths are ever modified that have been mentioned in the config. Also, a very similar scenario works in the demo where the page.title and page.subtitle properties remain unchanged and only page.counter is touched.

The problem here seems to be with your root reducer that does not recursively reconcile state on the HYDRATE action. You may consider handling the HYDRATE action in each of your individual reducers instead (see the demo for an example). Hope that helps!