8

I'm trying to implement redux-toolkit in my Next.js project without losing the option of SSR for the data I'm fetching from an external API. I have followed the example in next.js GitHub but doing so led to not having SSR when fetching data in my redux slice. I would like to know how I can fetch data and save that data in the Redux state. this is what I've written: this is the store.js file

export const store = configureStore({
  reducer: {
    users: usersReducer,
  },
});

the _app.js file

import { Provider } from 'react-redux';
import { store } from '../app/store';

const MyApp = ({ Component, pageProps }) => {
  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  );
};

export default MyApp;

the usersSlice.js file

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

const initialState = {
  items: null,
  status: 'idle',
  error: null,
};

export const fetchUsers = createAsyncThunk('users/fetchUsers', async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users');
  const users = await res.json();

  return users;
});

const usersSlice = createSlice({
  name: 'categories',
  initialState,
  reducers: {},

  extraReducers: {
    [fetchUsers.pending]: (state, action) => {
      state.status = 'loading';
    },

    [fetchUsers.fulfilled]: (state, action) => {
      state.status = 'succeeded';
      state.items = action.payload;
    },

    [fetchUsers.rejected]: (state, action) => {
      state.status = 'failed';
      state.error = action.error.message;
    },
  },
});

export default usersSlice.reducer;

and finally where the page I'm fetching the data from:

export default function Home() {
  const dispatch = useDispatch();
  const users = useSelector((state) => state.users.items);
  useEffect(() => {
    dispatch(fetchUsers());
  }, [dispatch]);

  return (
    <div>
      <h1>users</h1>
      {users &&
        users.length &&
        users.map((user) => <p key={user.id}>{user.name}</p>)}
    </div>
  );
}

If I fetch data through dispatching the fetchUsers function it won't have SSR, and if I use getServerSideProps it won't be saved in redux state. I'm clueless

yalda karimi
  • 81
  • 1
  • 3

1 Answers1

0

If you are okay to use Redux instead of redux-toolkit then follow this example [https://github.com/vercel/next.js/blob/canary/examples/with-redux-persist]Officail Example form Vercel/next.js. I too facing some issue when i am writing SSR code for Redux persist with redux toolkit. The work is currently in progress. Will share the code when it is available. Sis

Md Irshad
  • 19
  • 4