Skip to content

Instantly share code, notes, and snippets.

@pffigueiredo
Created May 11, 2022 18:24
Show Gist options
  • Save pffigueiredo/ef7516131a1ea74b2fed0d232a5e2902 to your computer and use it in GitHub Desktop.
Save pffigueiredo/ef7516131a1ea74b2fed0d232a5e2902 to your computer and use it in GitHub Desktop.
useFetchReducer
import React from "react";
export function useFetchReducer(initialData = null) {
const initialState = {
status: "idle",
data: initialData,
error: null
};
function fetchReducer(currentState, action) {
switch (action.type) {
case "FETCH":
return {
...currentState,
status: "loading"
};
case "RESOLVE":
return {
status: "success",
data: action.data,
error: null
};
case "REJECT":
return {
data: null,
status: "failure",
error: action.error
};
default:
return currentState;
}
}
return React.useReducer(fetchReducer, initialState);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment