redux-support
v0.0.1
Published
Third-party library that helps you write Redux logic easily and simply.
Downloads
2
Maintainers
Readme
Redux Support
Third-party library that helps you write Redux logic easily and simply.
Features
- createAction - Create an action object without payload.
const addNumberAction = createAction("ADD_NUMBER");
// { type: 'ADD_NUMBER' }
- createPayloadAction - Create an action object with payload.
const addNumberWithPayloadAction = createPayloadAction<number>(
"ADD_NUMBER_PAYLOAD",
2
);
// { type: 'ADD_NUMBER_PAYLOAD', payload: 2 }
- createAsyncActionType - Create action types required for asynchronous processing.
const [REQUEST, SUCCESS, FAILURE] = createAsyncActionType("GET_USER");
// [ 'GET_USER_REQUEST', 'GET_USER_SUCCESS', 'GET_USER_FAILURE' ]
- createAsyncHandler - Handle REQUEST, SUCCESS, and FAILURE actions and change the async state.
The first parameter receives a action-head type. This is to handle REQUEST, SUCCESS, FAILURE action.
What's the type of action head? Example) In case of USER_REQUEST, USER is the head type.
The second parameter conveys the property name of the object to be created by createAsyncState. Then it will work as follows. (I'll take the "REQUEST" status as an example.
{
user : {
loading: true,
data: null,
error: null
}
}
The actual move ↓
const userHandler = createAsyncHandler("USER", "user");
const userReducer = (state: AnyState, action: PayloadAction) => {
switch (action.type) {
case "USER_REQUEST":
case "USER_SUCCESS":
case "USER_FAILURE":
return userHandler(state, action);
}
};
userReducer(
{ user: {} },
{
type: "USER_SUCCESS",
payload: { id: 2, name: "Hong-JunHyeok" },
}
);
/*
{
user: {
loading: false,
data: { id: 2, name: 'Hong-JunHyeok' },
error: null
}
}
*/
- createLoadingState, createSuccessState, createFailureState - Create a state for the Async state.
switch (action.type) {
case REQUEST:
return {
...state,
...createLoadingState(),
};
case SUCCESS:
return {
...state,
...createSuccessState(action),
};
case FAILURE:
return {
...state,
...createFailureState(action),
};