Search code examples
reactjsreduxnext.jsredux-saga

Redux saga called multiple times (2 or 3 times) Nextjs


I am using Redux and Redux saga with Nextjs, i wrapped the store on _app.js file and when i call the api with post or get requests Redux-Saga is getting called at least two times, specially for post requests for example if i want to register a user using the api it is registering the user two times on the database PS: I am using rootSaga and i am not calling a saga twice there This is my store file:

import { createStore, applyMiddleware, compose } from "redux";
import createSagaMiddleware from "redux-saga";
import reducers from "./reducers";

import sagas from "./sagas";

const sagaMiddleware = createSagaMiddleware();

const middlewares = [sagaMiddleware];
export function configureStore(initialState) {
  const store = createStore(
    reducers,
    initialState,
    compose(applyMiddleware(...middlewares))
  );

  sagaMiddleware.run(sagas);

  if (module.hot) {
    module.hot.accept("./reducers", () => {
      const nextRootReducer = require("./reducers");
      store.replaceReducer(nextRootReducer);
    });
  }

  return store;
}

export const wrapper = createWrapper(configureStore, { debug: true });

And this is my _app.js file

import "../styles/styles.global.scss";
import "../styles/Home.module.scss";
import React from "react";

import App, { Container } from "next/app";
import { Provider, connect } from "react-redux";

import withRedux from "next-redux-wrapper";
import { configureStore, wrapper } from "../libs/store";
const context = React.createContext(undefined);


class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { ...pageProps };
  }

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

Thank you.


Solution

  • I Fixed it by removing the provider from _app.js and deleting _document.js PS: This solutions is for Nextjs >= 10.0.0