Skip to content

Instantly share code, notes, and snippets.

@icarus-sullivan
Created July 4, 2019 18:26
Show Gist options
  • Save icarus-sullivan/d84793a6f58edae1dc1a60928cca2a54 to your computer and use it in GitHub Desktop.
Save icarus-sullivan/d84793a6f58edae1dc1a60928cca2a54 to your computer and use it in GitHub Desktop.
Keeping track of asyncronous calls with reducer
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