Redux store reset on route change on his own with nextJS

Viewed 1966

Hello I'm having an issue with Redux and NextJS, when I'm loging in my Application with an API, the information of my user is perfectly stored in the redux store, thank's to reduxApiMiddleware, but when I reload my browser or change route my store come back to it's initial state :/.

I didn't really find a way to solve that, I tryed using redux-persist and all but nothing work

here is my _app.js file :

 // pages/_app.jsx
import React from "react";
import {createStore,applyMiddleware} from "redux";
import {Provider} from "react-redux";
import App,{Container} from "next/app";
import withRedux from "next-redux-wrapper";
import reducer from '../redux/reducers/index'
import { apiMiddleware } from "redux-api-middleware";
import { PersistGate } from 'redux-persist/integration/react';


/**
* @param {object} initialState The store's initial state (on the client side, the state of the server-side store is passed here)
* @param {boolean} options.isServer Indicates whether makeStore is executed on the server or the client side
* @param {Request} options.req Node.js `Request` object (only set before `getInitialProps` on the server side)
* @param {Response} options.res Node.js `Response` object (only set before `getInitialProps` on the server side)
* @param {boolean} options.debug User-defined debug flag
* @param {string} options.storeKey The key that will be used to persist the store in the browser's `window` object for safe HMR
*/

const createStoreWithMiddleware = applyMiddleware(apiMiddleware)(createStore);

export function configureStore(initialState,options) {
    return createStoreWithMiddleware(reducer, initialState);
  }


class MyApp extends App {
    static async getInitialProps({Component, ctx}) {
        // We can dispatch from here too
        // ctx.store.dispatch({type: 'FOO', payload: 'TOTO'});

        const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {};

        return {pageProps};
    }

    render() {
        const {Component, pageProps, store} = this.props;
        return (
                <Provider store={store}>
                        <Component {...pageProps} />
                </Provider>
        );
    }   
}
export default withRedux(configureStore)(MyApp);

And to connect a component or Page to my store this is how I do it :

export default connect(state=>state)(Register)
1 Answers

There are several ways to do this;

1 Write user information to localStorage.When reload browse, I load the data back to redux in the useEfect

2 use next/link

Related