Created
July 4, 2019 18:26
-
-
Save icarus-sullivan/d84793a6f58edae1dc1a60928cca2a54 to your computer and use it in GitHub Desktop.
Keeping track of asyncronous calls with reducer
This file contains hidden or 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 } from 'react'; | |
const config = [ | |
() => ({ loading: true }), | |
(data) => ({ loading: false, data }), | |
(error) => ({ loading: false, error }), | |
]; | |
const asyncReducer = (_, { type, payload }) => config[type](payload); | |
export const useAsync = (fn, ...args) => { | |
const [state, _dispatch] = useReducer(asyncReducer, { | |
loading: false, | |
}); | |
const dispatch = () => { | |
_dispatch({ type: 0 }); | |
Promise.resolve(fn(...args)) | |
.then((payload) => _dispatch({ type: 1, payload })) | |
.catch((e) => _dispatch({ type: 2, payload: e })); | |
} | |
return { | |
dispatch, | |
...state, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment