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')
)