Last active
October 30, 2019 05:16
-
-
Save GiambiHuang/57ad84a09acd879a263f088034863f09 to your computer and use it in GitHub Desktop.
State Management with React hooks and mock react-promise-middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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