I'm trying to setup Redux to replace recoil and would like to keep the implementation style of recoil. One where you can do something like
A) setState({ name: 'tim', id: 5 })
or
B) setState(({name}: User) => ({ name, id: 5 }));
I tried with
type PropertyFunction<T> = (newState: Partial<T>) => T;
type StateSetter<S> = Partial<S> | PropertyFunction<S>;
export const stateSetter = <T>(dispatch: Dispatch, setAction: ActionCreatorWithPayload<Partial<T>>, state: T) => {
return (newState: StateSetter<T>) => {
if (typeof newState === 'function') {
dispatch(setAction(newState(state)));
} else {
dispatch(setAction(newState));
}
};
};
But the stateSetter function does not accept functions, only (a user)
Meaning I can only do A) but not B)
Here is my simple setState reducer
export const alertSlice = createSlice({
name: 'user',
initialState,
reducers: {
set: (state: AlertState, action: PayloadAction<Partial<AlertState>>) => {
state = { ...state, ...action.payload };
},
},
});
export const { set: setAlertAction } = alertSlice.actions;
Can you use other alternatives like MobX, Jotai or Valtio?
Redux is really not meant to be used like this - actions should describe events happening in your application and the logic calculating the next state should live in the reducer.
If you want the logic outside the store, you will be off much better with another library and it will feel a lot "less weird" to use.