0

I am trying to add redux to Next.js. It is not working Ok
This is my reducerSlice file

import { createSlice } from '@reduxjs/toolkit';
import { HYDRATE } from 'next-redux-wrapper';
import { AppState } from '..';

export const ProfileSlice = createSlice({
  name: 'profile',

  initialState: {
    name: [] as any
  },

  reducers: {
    setProfileData: (state, action) => {
      state.name = [...state.name, action.payload];
    }
  },

  extraReducers: {
    [HYDRATE]: (state, action) => {
      if (!action.payload.profile.name) {
        return state;
      }
      const nextState = {
        ...state, // use previous state
        name: [...state.name, ...action.payload.profile.name]
      };
      return nextState;
    }
  }
});

export const { setProfileData } = ProfileSlice.actions;
export const selectProfile = (state:AppState)=>state.profile;

export default ProfileSlice.reducer;

When I use server side rendering to dispatch data to the store a single value is stored okay but when i use array the hydration is called multiple times You can see in this image Emma is logged 4 times I don't know what to do

Here is how I used SSR in profile file

export const getServerSideProps = wrapper.getServerSideProps(store => async ({ query }) => {
    console.log('store state on the server before dispatch', store.getState());
    const response = await fetch(
        `https://reqres.in/api/users/${Math.floor(Math.random() * 10 + 1)}`
    );
    const { data } = await response.json();
    const data2 = data.first_name;
    store.dispatch(setProfileData(`${data.first_name}`));
    return {
        props: {
          data2
        }
    };
});
juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • Need to show more implementation around the store.getState() If its just in the component and on in a component did mount or useEffect it will be triggered every-time there is a rerender. So that behavior wouldn't be surprising. – Colin Hale Jul 21 '22 at 22:15

0 Answers0