2

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

Faizan Tariq
  • 351
  • 4
  • 14
  • What do you find confusing about these? Also, are you using `getServerSideProps` at all? If yes, please share that code. – phry Nov 28 '22 at 19:27
  • The confusing is that in the logs (screenshot above) cart reducer has data as empty [] although i added items in cart and it was showing up in UI but somehow not updating here. So not sure if there are multiple stores which got created and not synced. – Faizan Tariq Nov 28 '22 at 19:34
  • Yes I am using getServerSideProps. I have added code snippet above – Faizan Tariq Nov 28 '22 at 19:36
  • If you are doing those logs on the server: the server starts empty at every render and never knows about the state on the client - how could it? New state from the server is transported to the client and "synced in" (if you wire that up), but never from client to server. – phry Nov 28 '22 at 20:19
  • Yes these are from server logs and I got it, but is there any way i remove cart: data [] from server logs. Also i see the same empty array even in browser console which is client logs – Faizan Tariq Nov 28 '22 at 20:47
  • No, because that is part of your Redux store - you configure your store with it, no matter if used or not. And yes, on the browser I would assume that it is empty as well - until you fill it? – phry Nov 28 '22 at 22:43
  • Couple of questions: do we need to setup 2 different redux stores one for server side query and one for client side or same redux store should be used. What the recommended approach? And I am filling it but in browser console it showing empty – Faizan Tariq Nov 28 '22 at 23:18
  • 1
    Use the same. Don't look at the console in the browser, but at the Redux Devtools. Maybe you are logging at a bad moment in time. – phry Nov 28 '22 at 23:50
  • Thanks for the help. With Redux Dev Tool my confusion is clear and thankyou for resolving my query. – Faizan Tariq Nov 29 '22 at 00:31

0 Answers0