I'm implementing a simple favorites list. Currently there's no backend part so it will be persisted in localStorage. In the future it may become an API call.
Is it okay to call localStorage.setItem
and localStorage.getItem from within a rtk slice?
For example:
createSlice({
name: "slice",
initialState,
extraReducers: extraReducers,
reducers: {
setLocalStorageThing: (
state,
action: PayloadAction<{ payload: string }>
) => {
let localStoragething= JSON.parse(
localStorage.getItem("key")
);
if (localStorageThing !== payload) {
localStorage.setItem(
"key",
JSON.stringify(payload)
);
}
},
}
Alternatively, is this possible as a thunk? Ultimately I'd like to be able to use the useSelector hook to access this information, so when the swap happens I only have to change the action/reducer in the slice. This seems like a side effect, but I'm not sure the harm in it. It has already been done else where in the code without issue (so far).