Skip to content

Instantly share code, notes, and snippets.

@GiambiHuang
Last active October 30, 2019 05:16
Show Gist options
  • Save GiambiHuang/57ad84a09acd879a263f088034863f09 to your computer and use it in GitHub Desktop.
Save GiambiHuang/57ad84a09acd879a263f088034863f09 to your computer and use it in GitHub Desktop.
State Management with React hooks and mock react-promise-middleware
import React, { useReducer, useCallback, useContext } from 'react';
const initialState = {
data: '',
isPending: false,
};
export const constant = {
FETCH_DATA: 'FETCH_DATA',
FETCH_DATA__PENDING: 'FETCH_DATA__PENDING',
FETCH_DATA__REJECTED: 'FETCH_DATA__REJECTED',
};
const reducer = (state, action) => {
switch (action.type) {
case constant.FETCH_DATA:
return {
...state,
data: action.payload,
isPending: false,
};
case constant.FETCH_DATA__PENDING:
return {
...state,
isPending: true,
};
default:
return state;
}
}
export const CustomContext = React.createContext({});
export const CustomProvider = ({ chidren }) => {
const [state, dispatch] = useReducer(reducer, initialState);
// handle api call [promise-middleware]
const useApiRequest = useCallback((type, payload) => {
// Pending
dispatch({ type: `${type}__PENDING` });
const handleFulfill = val => {
dispatch({ type, payload: val });
return val;
}
const handleRejected = val => {
dispatch({ type: `${type}__REJECTED`, payload: val });
return val;
}
return payload
.then(handleFulfill)
.catch(handleRejected)
}, []);
const request = {
getData: () => useApiRequest(constant.FETCH_DATA, fetch('URL')),
};
return (
<CustomContext.Provider value={{ state, dispatch, request }}>
{children}
</CustomContext.Provider>
)
};
export const useCustomContext = () => useContext(CustomContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment