Created
May 11, 2022 18:24
-
-
Save pffigueiredo/ef7516131a1ea74b2fed0d232a5e2902 to your computer and use it in GitHub Desktop.
useFetchReducer
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 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