I'm having trouble refactoring with createSlice, I'm a beginner with redux-toolkit and have looked through the documentation but still having problems.if someone could point me in the right direction that would be fantastic. This is the working code
const SET_ALERT = 'setAlert';
const REMOVE_ALERT = 'alertRemoved';
export const setAlert =
(msg, alertType, timeout = 5000) =>
(dispatch) => {
const id = nanoid();
dispatch({
type: SET_ALERT,
payload: { msg, alertType, id },
});
setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout);
};
const initialState = [];
export default function alertReducer(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case SET_ALERT:
return [...state, payload];
case REMOVE_ALERT:
return state.filter((alert) => alert.id !== payload);
default:
return state;
}
}
Your current
setAlertaction creator creates a thunk action (an action which takesdispatchas an argument) so it cannot be an action creator that is automatically generated bycreateSlice.createSlice
You can keep the setup very similar to what you have now. You would have two separate actions for setting and removing an alert and a thunk for dispatching both. The underlying basic actions can be created with
createSlice.CodeSandbox
createAsyncThunk
This next section is totally unnecessary and overly "tricky".
We can make use of
createAsyncThunkif we consider opening the alert as the 'pending' action and dismissing the alert as the 'fulfilled' action. It only gets a single argument, so you would need to pass themsg,alertType, andtimeoutas properties of an object. You can use the unique id of the thunk which isaction.meta.requestIdrather than creating your own id. You can also access the arguments of the action viaaction.meta.arg.You can still use
createSliceif you want, though there's no advantage overcreateReducerunless you have other actions. You would respond to both of the thunk actions using theextraReducersproperty rather thanreducers.example component
CodeSandbox