Skip to content

Instantly share code, notes, and snippets.

@TobiahRex
Last active April 25, 2019 02:16
Show Gist options
  • Save TobiahRex/fbc5860104ea4c15b283ab98fbaf02b6 to your computer and use it in GitHub Desktop.
Save TobiahRex/fbc5860104ea4c15b283ab98fbaf02b6 to your computer and use it in GitHub Desktop.
Using useReducer with an initialization function in first arguments place.
import { v4 as generateId } from 'immutable';
//------------- CUSTOM HOOK -------------
export function useSetState(initialState) {
const [state, setState] = useReducer((prevState, action) => {
// HERE we can have normal reducer logic to handle the action and create a "newState"
if (someAction === someValue) {
if (!state.reqids.includes(action.meta.reqId)) return state;
// do something with the action.payload
}
// finally, return the new state
return ({
...prevState,
...newState,
}), initialState);
}
return [state, setState];
}
//------------- Module Logic -------------
function SomeModule() {
const [reqIds, setReqIds] = useState([]);
const [state, setState] = useSetState({ reqIds });
function getSomeData(reqId) {
const newReqId = generateId();
setReqIds(newReqId);
getSingle(
['ASSET_COMPANY_PROFILE'],
[wsDispatch(
setState(
(msg) => ({
type: types.RECEIVE_COMPANY_INFO,
payload: msg.payload,
meta: { newReqId } // pass in a unique id generated by the module
})
)
)],
[{ type: 'ASSET_COMPANY_PROFILE', payload: { providerId } }],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment