React's Redux persist is causing a duplication of requests being sent

I am currently utilizing redux-persist along with Redux Toolkit. I have observed a peculiar behavior where, upon changing the slice (RTK), a request is sent to the server. When using redux-persist without a persister, only one request is made as expected. However, when the persister is connected, two identical requests are sent simultaneously.

This snippet of code demonstrates how the request is being sent:

  const {
    simpleOutgoingData,
  } = useTypedSelector(({ simpleMortgage }) => simpleMortgage)

  const { postSimpleMortgageCalc } = useActions()

  useEffect(() => {
    postSimpleMortgageCalc(simpleOutgoingData)
  }, [simpleOutgoingData])

Below is the code for the 'slice':

const simpleOutgoingData = createSlice({
  name: 'simpleOutgoingData',
  initialState: {
    target: 'payment',
    mortgageAmount: 500000,
    loanType: 'regular',
    interestRate: 1.6,
    amortizationMonths: 300,
    isIncludeAmortizationTable: true,
    rateTermMonths: 60,
    paymentFrequency: 'monthly',
    extraPayment: 0,
    annualPrepayment: 0,
    oneTimePrepayment: 0,
    rateType: 'variable',
    rateCompounding: 'semi-Annual',
  } as SimpleOutgoingDataType,
  reducers: {
    setSimpleOutgoingData: (
      state,
      { payload }: PayloadAction<SimpleOutgoingDataType>,
    ) => ({
      ...state,
      ...payload,
    }),
  },
  extraReducers: {
    [clearStore.type]: () => {},
  },
})

Here's the saga related to this functionality:

function* postSimpleMortgageCalc(
  action: ReturnType<typeof actions.postSimpleMortgageCalc>
) {
  const { payload } = action

  yield put(actions.setIsLoading(true))

  try {
    const {
      data: { result },
    } = yield call(() => API.simpleMortgageCalc.post(payload))

    yield put(
      actions.setSimpleMortgageData({
        principalPayment: 0,
        interestPayment: 0,
        ...result,
      })
    )
  } catch (e) {
    console.log(e)
  } finally {
    yield put(actions.setIsLoading(false))
  }
}

export function* watchSimpleMortgageSaga() {
  yield takeLatest(actions.postSimpleMortgageCalc.type, postSimpleMortgageCalc)
}

Below is the root saga:

export default function* RootSaga() {
  yield all([fork(watchSimpleMortgageSaga)])
}

The following code represents the root Reducer:

export default combineReducers({
  simpleMortgage: simpleMortgageReducer
})

This portion showcases the store index file:

const persistConfig = {
  key: 'root',
  storage,
  stateReconciler: autoMergeLevel2 // see "Merge Process" section for details.
}

const pReducer = persistReducer<StateType, any>(persistConfig, RootReducer)

const sagaMiddleware = saga()

const store = configureStore({
  reducer: pReducer,
  middleware: [
    ...getDefaultMiddleware({ thunk: false, serializableCheck: false }),
    sagaMiddleware
  ],
  devTools: true
})

sagaMiddleware.run(RootSaga)

export type RootState = ReturnType<typeof store.getState>

export default store

export const persistor = persistStore(store)

Lastly, this segment presents the app index file:

ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <React.StrictMode>
        <App domElement={1} />
      </React.StrictMode>
    </PersistGate>
  </Provider>,
  document.getElementById('root')
)

Answer №1

The reason for this behavior is the presence of react strictmode. If you disable it, the request will only be made once.

Also, you can take a look at: https://reactjs.org/docs/strict-mode.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigate through collections of objects containing sub-collections of more objects

The backend is sending an object that contains an array of objects, which in turn contain more arrays of objects, creating a tree structure. I need a way to navigate between these objects by following the array and then back again. What would be the most ...

Tips for navigating to a specific row within a designated page using the Angular Material table

Utilizing angular material, I have set up a table with pagination for displaying data. When a user clicks on a row, they are redirected to another page. To return to the table page, they must click on a button. The issue arises when the user needs to retu ...

Verification of custom data type validation

I am puzzled by the behavior of this custom type state: interface DataType { [key: string]: string;} const [data, setData] = React.useState<DataType>({}); When I attempt to execute console.log(data === {}) It surprisingly returns false. Why ...

Guide to leveraging clsx within nested components in React

I am currently using clsx within a React application and encountering an issue with how to utilize it when dealing with mappings and nested components. For instance: return ( <div> <button onClick={doSomething}>{isOpened ? <Component ...

To successfully import files in Sveltekit from locations outside of /src/lib, make sure to include the .ts extension in the import statement

Currently, I am working on writing tests with Playwright within the /tests directory. I want to include some helper functions that can be placed in the /tests/lib/helpers folder. When the import does not specifically have a .ts extension, tests throw a mo ...

The use of p-message in Angular's PrimeNg library is not permitted

Hey there, I'm having a bit of trouble with the p-message Tag in Angular. I believe I've imported it correctly as shown below. import { MessageModule } from 'primeng/message'; imports: [ .... MessageModule, ... In the ...

ts-node: The colon symbol was not expected in this context

As I work on developing a backend server for my application, I made the decision to switch from using babel-node as the executor to utilizing ts-node. The command defined in my package.json file is: "server": "cd server && ts-node --project tsconf ...

Can all objects within an interface be iterated through in order to retrieve both the key and its corresponding value?

I have created an interface that is capable of accepting a variety of search criteria and then passing it to a service that will incorporate those values into the service URL. I am wondering if there is a way to iterate through all the objects in the inter ...

Attempting to adhere to the prescribed Cypress tutorial is resulting in various errors related to being "compiled under '--isolatedModules'"

I am new to using Cypress and I have been following the helpful tutorial on testing your first application. However, I have encountered some compiler issues in the third section. Following the instructions, I created a custom command but I am receiving th ...

Error message: The database query function is encountering an issue where the property 'relation.referencedTable' is undefined and cannot be accessed

Currently, I am working with two schemas named products.ts and category.ts. The relationship between these files is defined as one-to-many. In the products.ts file: import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core"; import ...

In the application I'm developing, I'm utilizing React alongside TypeScript, making use of the useContext and useReducer hooks. However, I've encountered an issue where the dispatch function is not being

Currently, I have implemented a feature where two lists are displayed as cards based on one main list of objects. The goal is to toggle the 'favorite' value for each card item when the star button is clicked. This action should move the favorited ...

Issue: The function (0, react__WEBPACK_IMPORTED_MODULE_1__.useActionState) is not recognized as a valid function or its output is not iterable

I found a great example of using useActionState at this source. Currently, I am implementing it in my project with Next.js and TypeScript. app/page.tsx: "use client"; import { useActionState } from "react"; import { createUser } from ...

Encountering an error when attempting to access undefined property while using a method as a callback

Exploring OOP and angular is new to me. I am currently trying to implement a reusable table with pagination that triggers an API request when the page changes (pagination within the table component). The issue arises when I attempt to access my method usi ...

How can I use the target type (and maybe even the property type) as a type parameter within a decorator?

In the process of incorporating a deep-watch property decorator in Angular, the following usage has been implemented: @Component({ /* ... */ }) export class AppComp { @Watch( 'a.b.c', function (last, current, firstChange) { // ca ...

Issue encountered while attempting to launch Angular2 project

Having trouble running my Angular2 project, every time I try to use the ng serve command I get an error: Here is the link: I've installed angular 2 using angular-cli with the following steps: 1. sudo npm install -g angular-cli 2. sudo ng new mi-apl ...

Leverage the event handler within a React Component when working with TSX tags

Is there a way to expose an event handler that is defined within a React Component in an HTML-like tag? For example: <MyComp param1="abc" param2="def" onDoSomething={this.someMethod} /> I am trying to define the onDoSomething event, but currently I ...

Circular dependency has been detected when using the ESLint with TypeORM

Having two entity typeorm with a bi-directional one-to-one relationship: Departament: @Entity('Departament') export default class Departament { @PrimaryGeneratedColumn() id: string; @Column() departament_name: string; @OneToOne(type ...

Step-by-step guide to creating a custom wrapper in React that modifies the props for a component

Exploring React components for the first time and seeking assistance. I am interested in dynamically wrapping one component inside another and modifying its props. For instance, considering the following component: If we want to pass the key3 from a wrapp ...

Using TypeScript, you can pass an object property name as a function argument while ensuring the type is

How can I define a type in a function argument that corresponds to one of the object properties with the same type? For instance, if I have an object: type Article = { name: string; quantity: number; priceNet: number; priceGross: number; }; and I ...

Using @Input to pass data from a parent component to a

Looking to modularize the form code into a separate component for reusability? Consider using @Input and referencing it in the HTML to pass values to the post method. Here's how you can achieve this: Previously, everything worked smoothly when all th ...