Language used : JS with REACT - REDUX TOOLKIT (and in this case redux-persist)
Here is the context: I have a form and when the user refresh the page, i keep the state with redux persist. For example, we have an input text, the user write something. If he refresh, the text will be kept
Here is my problem : I have a button. On Click i would like to clean the state and reset the form to his initial state.
I only know how to clean ALL redux persist state with
<p onClick={() => persistor.purge()}> PURGE</p>
Here is my store
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import storage from 'redux-persist/lib/storage';
import { persistReducer, persistStore } from 'redux-persist';
import thunk from 'redux-thunk';
// persistor import
import { formReducer } from '../features/form.slice';
import { usersReducer } from '../features/users.slice';
const persistConfig = {
key: 'root',
storage,
blacklist: ['users'],
};
const usersConfig = {
key: 'users',
storage,
blacklist: ['usersToDelete'],
};
const appReducer = combineReducers({
form: formReducer,
users: persistReducer(usersConfig , usersReducer),
});
const persistedReducer = persistReducer(persistConfig, appReducer);
export const store = configureStore({
reducer: persistedReducer,
middleware: [thunk],
});
export const persistor = persistStore(store);
Here my button
import React from 'react';
export const Reset= () => {
return (
<button
onClick={() => console.log('i want to reset the form state to his initial state')}
className="button rounded "
>
Reset
</button>
);
};
Maybe i can do an action with redux-toolkit ( resetForm) and onClick do this action but how to tell redux-persist to clean ? thank you
CodePudding user response:
As you can read on the end of the section type Persistor:
purge()
method only clear the content of the storage, leaving the internal data of redux untouched. To clean it instead, you can use the redux-reset module.
You are looking for the way how to reset redux form state (and it will be automatically persisted to storage). The best way is to create resetForm action and in reducer set it's state to initialValue (empty not filled form).
CodePudding user response:
You need a redux action creator since you want to:
- Modify the state to its default state value
- Do a side effect: Call persistor.purge()
Button onclick should dispatch the action creator function