redux-CRUDaxe-thunk
Why
This library was created for simplify of describing narrow propose Redux(redux-thunk) modules.
Long story
General way
First, we all split out Redux modules, using this structure:
- actions - just strings with actions names
- action creators - functions, which returns action object
- reducer - pure function to handle actions
Redux is beautiful tool, but it requires a lot of writing. So, here i'll not show any examples because it totally described in documentation.
DUCK
Put all together +Then some of us decided that it will be more clear to put all definitions of Redux module in one file.
Example:
// Actionsconst REQUEST = 'some-namespace/REQUEST';const RECEIVE = 'some-namespace/RECEIVE';const ERROR = 'some-namespace/ERROR'; // Action creatorsconst fetchSomeNamespace = type: REQUEST; const receiveSomeNamespaceData = payload type: RECEIVE; const setSomeNamespaceError = payload type: ERROR; // Async actionsconst requestSomeNamespace = async { ; try const data = await ; ; catch error ; }; // Reducerconst reducer = { if type === REQUEST return error: null data: null isInProcess: true ; if type === RECEIVE return error: null data: payload isInProcess: false ; if type === ERROR return error: payload data: null isInProcess: false ; return state;};
I should notify you, that I worked only on simple cases of Redux modules. It has 3 fields of data: isInProcess, data, error. You'll see example soon.
It looks better, but I decided to move forward...
More functions
I hate if
and switch
=), and I suppose you all know
other way to make some decision in code: dictionaries.
Example (here I show only changes):
// Action handlersconst handleFetch = error: null data: null isInProcess: true; const handleReceive = error: null data: payload isInProcess: false; const handleErrors = error: payload isInProcess: false data: null; // Reducerconst reducer = { const handlersByActionType = ERROR: handleErrors REQUEST: handleFetch RECEIVE: handleReceive ; const handler = handlersByActionTypetype; if handler return ; return state;};
Here we just moved our pure reducer parts in separated pure functions.
useSelector
hook
Awesome guys from Facebook gave us React hooks.
Then, Redux added hooks too.
And one of the most used hook is useSelector
.
It has simple API - only you need is just pass function to it. This function should describe how to get the value from Redux store.
I love FP, and I hate repeating:
useSelector(state => state.someModule.value)
Isn't it more elegant way: useSelector(selectSomeModuleValue)
?
Redux module selectors
So, we have Redux module namespace. I call it moduleName
.
// Do you remember our action names? Here you are:const REQUEST = 'some-namespace/REQUEST';const RECEIVE = 'some-namespace/RECEIVE';const ERROR = 'some-namespace/ERROR';
Let's remove some repeating:
// store/utils/getActionNameForModule/index.jsconst getActionNameForModule = `/`; // store/some-namespace/index.jsconst moduleName = 'some-namespace';const getActionName = ; // Actionsconst REQUEST = ;const RECEIVE = ;const ERROR = ;
And add same thing for data selectors:
// store/utils/getPureSelectorForModuleState/index.jsconst getPureSelectorForModuleState = { // Implementation here...}; // store/some-namespace/index.jsconst moduleName = 'some-namespace'; const getSelectorFor = ; const selectError = ;const selectData = ;const selectIsInProcess = ;
Now in your component you may do this:
const data = ;
Yes, there is exists a possibility of selectors names collision, but wait for a moment
One of benefits of this decision: this selectors are pretty simple composes with reselect selectors.
Few steps of thinking and composition later... we finally got
getProcedure
and getCRUD
functions.
API
getProcedure
// store/login/index.js;; // API request const loginProcedure = ; // store/index.js;
getProcedure
output signature
actionCreatorsByType
- object that contains action creators by name (ERROR, RECEIVE, REQUEST, RESET). DEPRECATED, useactions
insteadactions
- object that contains action creators by name (ERROR, RECEIVE, REQUEST, RESET)init
- function which you use while adding the procedure in store reducers listreducer
- reducer functionrequest
- async action creator, which you may dispatch to produce http requestselectAll
- function foruseSelector
hook;useSelector(procedureName.selectAll)
returns full procedure state, object with fieldsdata, error, isInProcess
selectors
- object, that contains functions by namesdata
,error
,isInProcess
, that may be used foruseSelector
like this:useSelector(procedureName.selectors.data)
getCRUD
; // API functions;;; const userCRUD = ; // store/index.js;
Extra options
stateDefaults
Default state of every procedure is:
data: null error: null isInProcess: false
So you can provide your onw default state. Every options in stateDefaults
object are optional
// store/login/index.js;; // API request const loginProcedure = ;
sideEffects
You may want always do something on response and error, so:
// store/login/index.js;; // API request const loginProcedure = ;
Both of options -
data
anderror
- are optional
mock
Finally you may mock your response, when your API is not ready, but you already have a contract.
// store/login/index.js;; // API request const loginProcedure = ;
Side effects in components
When you use dispatch(procedureName.request())
, you may possibly want to do redirect,
or any other action, when request will return the data or error.
To do this, you should include function handleResponse
from the library:
// Some component; // Somewhere in component ;
handleResponse
accepts three functions:
- handleSuccess
- handleError
- handleDefault
All of the functions are optional. So, if you only want to handle an error, you may
pass an identity
function as first argument
Usage in component
import React useState from 'react';import useDispatch useSelector from 'react-redux';import loginProcedure from '@store/login'; const LoginForm = const login = ; const dispatch = ; const loginValue setLoginValue = ; const passwordValue setPasswordValue = ; const handleSubmit = { e; ; }; const handleChange = { const name value = etarget; const setValue = name === 'login' ? setLoginValue : setPasswordValue; ; }; return <form => <input = ="Login" ="login" = /> <input = ="password" ="password" = /> <button>loginisInProcess ? 'Loading...' : 'Send'</button> </form> ;;
Procedure request accepts only one argument, so you need to pass all values you want, using just one object