question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Previous state rests on every navigation

See original GitHub issue

It was really hard to get here and after that, there are still problems getting Redux with Next js

store.js

import reducers from './rootReducer';
import { configureStore } from '@reduxjs/toolkit';
import { createWrapper, HYDRATE } from 'next-redux-wrapper';


const reducer = (state, action) => {
  if (action.type === HYDRATE) {
    let nextState = {
      ...state,
      ...action.payload, 
    };

    console.log(nextState);
    return nextState;
  } else {
    return reducers(state, action);
  }
};

const isDev = process.env.NODE_ENV === 'development';

const makeStore = (context) => {
  let middleware = [];

  const store = configureStore({
    reducer,
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware().concat(middleware),
    devTools: isDev,
    preloadedState: undefined,
  });

  return store;
};

export const wrapper = createWrapper(makeStore, { debug: isDev });

_app.js

import React from 'react';

import { wrapper } from '../redux/store';

const MyApp = ({ Component, ...rest }) => {
  return <Component {...rest} />;
};

export default wrapper.withRedux(MyApp);

slice.js

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

const initialState = {
  data: [],
};

const test1 = createSlice({
  name: 'test1',
  initialState,
  reducers: {
    update: {

      reducer: (state, { payload }) => {
        return { ...state, data: payload };
      },
    },
  },

});

export const TEST1 = createAsyncThunk(
  'ask',
  async (data, { rejectWithValue, dispatch }) => {
    try {
      const response = await fetch(
        'https://jsonplaceholder.typicode.com/posts'
      );
      const d = await response.json();

      dispatch(test1.actions.update(d));
      return d;
    } catch (error) {
      return rejectWithValue(error.response.data.error);
    }
  }
);

export default test1.reducer;

Home.js

import Head from 'next/head';
import Link from 'next/link';
import { useSelector } from 'react-redux';
import { wrapper } from '../redux/store';
import { TEST1 } from '../redux/test1/test';

function Home({ pageProps }) {
  const { data: data1 } = useSelector((state) => state.test1);
  const { data } = useSelector((state) => state.test);

  return (
    <div>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Link href="/test">
        <a>About Us</a>
      </Link>
      <h1>{pageProps.a}</h1>
      {/* {data && data.map((name) => <h1>{name.email}</h1>)} */}
    </div>
  );
}

export const getStaticProps = wrapper.getStaticProps(
  (store) => async (context) => {
    await store.dispatch(TEST1('1'));
    return {
      props: {},
    };
  }
);

export default Home;

TestPage.js

import React from 'react';
import { AskCallPost } from '../../redux/test/tes';
import { useSelector } from 'react-redux';
import Link from 'next/link';
import { wrapper } from '../../redux/store';

function Test({ pageProps }) {
  const { data: data1 } = useSelector((state) => state.test1);
  const { data } = useSelector((state) => state.test);
  console.log(data);
  console.log(data1);

  return (
    <div>
      <Link href="/">
        <a>home</a>
      </Link>{' '}
      {data && data.map((name) => <h1>{name.name}</h1>)}
    </div>
  );
}
export const getStaticProps = wrapper.getStaticProps(
  (store) => async (context) => {
    await store.dispatch(AskCallPost('hi'));
    return {
      props: {},
    };
  }
);

export default Test;

When navigating from Home to Test

WrappedApp created new store with withRedux(MyApp) {
  initialState: undefined,
  initialStateFromGSPorGSSR: { test: { data: [] }, test1: { data: [Array] } }

And when I come back

WrappedApp created new store with withRedux(MyApp) {
  initialState: undefined,
  initialStateFromGSPorGSSR: { test: { data: [Array] }, test1: { data: [] } }

I tried to attach the sandbox and it didn’t work error - hookwebpackerror: cannot read property 'replace' of undefined

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:15 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
Elabbasy00commented, Feb 8, 2022

Can you tell us about the correct way the docs are not clear enough

0reactions
Elabbasy00commented, Dec 6, 2022

check this on stackoverflow

Read more comments on GitHub >

github_iconTop Results From Across the Web

React Navigation re-render / reset previous page's state on ...
I am writing this article on react-navitagion for react-native cross-platform mobile app. It allows user to re-render or reset the route components when ......
Read more >
How preserve state when navigating from one route to the other
This my code: class Navigation extends React. Component { state = { language: "en", selectedCountry: "Cameroon" }; changeLanguage = (lang) => ...
Read more >
Navigation state reference
The navigation state is the state where React Navigation stores the navigation structure and history of the app. It's useful to know about...
Read more >
useLocation and useNavigate State (Redirect to ... - YouTube
useLocation and useNavigate State (Redirect to Previous Page on Login) - React Tutorial 45 · Key moments. View all · Key moments ·...
Read more >
Development of navigation network revealed by resting-state ...
Recent studies on development of the navigation network mainly examined activation changes in the medial temporal regions. It is unclear how the large-scale ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found