Store State Issues - Next Redux Wrapper vs Redux ToolKit

802 Views Asked by At

FYI: Everything is working fine and all the flows are working as expected but logs are confusing.

I am using Redux ToolKit for managing redux state & using Next Redux Wrapper for Server Side rendering and caching queries.

CartSlice.js

import { createSlice } from '@reduxjs/toolkit';

export const cartSlice = createSlice({
  name: 'cart',
  initialState: { data: [] },
  reducers: {
    addToCart: (state, action) => {
      const itemInCart = state.data.find((item) => item.id === action.payload.id);
      if (itemInCart) {
        itemInCart.quantity += action.payload.quantity;
      } else {
        state.data.push({ ...action.payload });
      }
    }
  },
});

export const cartReducer = cartSlice.reducer;
export const { addToCart } = cartSlice.actions;

ServiceApi.js

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { HYDRATE } from 'next-redux-wrapper'

export const serviceApi = createApi({
  reducerPath: 'serviceApi',
  baseQuery: fetchBaseQuery({ baseUrl: '<base-url>' }),
  extractRehydrationInfo(action, { reducerPath }) {
    if (action.type === HYDRATE) {
      return action.payload[reducerPath]
    } 
  },

  endpoints: (builder) => ({
    getItemById: builder.query({ query: (id) => `id/${id}` }),
    getItems: builder.query({ query: () => `/` }),
  }),
})

export const { getRunningQueriesThunk } = serviceApi.util
export const { useGetItemByIdQuery, useGetItemsQuery } = serviceApi
export const { getItemById, getItems } = serviceApi.endpoints;

store.js

import { configureStore } from '@reduxjs/toolkit'
import { serviceApi } from './serviceApi'
import { createWrapper } from "next-redux-wrapper";
import { cartSlice } from "./cartSlice";

export const store = configureStore({
  reducer: {
    [cartSlice.name]: cartSlice.reducer,
    [serviceApi.reducerPath]: serviceApi.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(serviceApi.middleware),
  })

const makeStore = () => store
export const wrapper = createWrapper(makeStore, {debug: true});

Using getServerSideProps

export const getServerSideProps = wrapper.getServerSideProps(
  (store) => async (context) => {
    const { id } = context.query;
    store.dispatch(serviceApi.endpoints.getItemById.initiate(parseInt(id)));
    await Promise.all(store.dispatch(serviceApi.util.getRunningQueriesThunk()));
    return {
      props: {},
    };
  }
);

And using wrappedStore

const { store, props } = wrapper.useWrappedStore(pageProps);

On the UI flows everything is working as expected and i am able to add items in the cart and i can see the store state is getting updated by looking the UI.

But the logs from next redux wrapper is confusing:

See this screenshot, i have items added in my cart (i.e. store state) but i see in the below logs its showing cart data as empty [] which is confusing

0

There are 0 best solutions below