- They propose to use
subscribe
for vanilla Redux here:
Where to write to localStorage in a Redux app?
- Here for Redux Toolkit he propose to sort out local storage write operation in a separate thunk, and make dispatch from one reducer to the thunk.
How to subscribe to state outside React component in Redux Toolkit?
What do you think?
Right now I have this simple solution, one reducer, it saves to state and to localStore also, I do not face any issue yet. Shall I change?
extraReducers: (builder) => {
builder
.addCase(me.fulfilled, (state, { payload }) => {
state.authnRes = payload
localStorage.setItem('authnRes', JSON.stringify(payload))
})
Shall I make a separate thunk, and move the localStorage.setItem('authnRes', JSON.stringify(payload))
into there?
He says:
Reducer is never an appropriate place to do this because reducers should be pure and have no side effects.
Do you see any drawback in this approach? Thunk fires an other thunk with local store operation.
export const loginEmail = createAsyncThunk(
`${namespace}/loginEmail`,
async (req: any, { dispatch }) => {
const { data } = await axios(req).then((res) => {
dispatch(persistAuthnUser(res.data)) // <--- here
return res
})
return data
}
)
and here persist
happens:
export const persistAuthnUser = createAsyncThunk(
`${namespace}/persistAuthnUser`,
async (data: any, { dispatch }) => {
return Promise.resolve().then(function () {
localStorage.setItem('authnRes', JSON.stringify(data))
})
}
)