Skip to content

Commit

Permalink
useReducer + useFetch
Browse files Browse the repository at this point in the history
  • Loading branch information
sahebmohammadi committed Nov 30, 2021
1 parent 504c357 commit 1c87bf5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
2 changes: 1 addition & 1 deletion custom-hook/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import useFetch from "./hook/useFetch";

function App() {
const { error, loading, data } = useFetch(
"https://jsonplaceholder.typicode.com/ussdsers"
"https://jsonplaceholder.typicode.com/users"
);

return (
Expand Down
47 changes: 34 additions & 13 deletions custom-hook/src/hook/useFetch.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,50 @@
import { useEffect, useState } from "react";
import { useEffect, useReducer } from "react";
import axios from "axios";

const initialSatate = {
error: null,
data: null,
loading: false,
};

const actions = {
fetchRequest: "FETCH_DATA_REQUEST",
fetchSuccess: "FETCH_DATA_SUCCESS",
fetchFailure: "FETCH_DATA_FAILURE",
};

function reducer(state, action) {
switch (action.type) {
case actions.fetchRequest: {
return { ...state, loading: true, error: null, data: null };
}
case actions.fetchSuccess: {
return { ...state, loading: false, error: null, data: action.payload };
}
case actions.fetchFailure: {
return { ...state, loading: false, error: action.payload, data: null };
}
default:
return state;
}
}

const useFetch = (url) => {
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null);
const [state, dispatch] = useReducer(reducer, initialSatate);

useEffect(() => {
setLoading(true);
setData(null);
setError(null);

dispatch({ type: actions.fetchRequest });
axios
.get(url)
.then((res) => {
setLoading(false);
setData(res.data);
dispatch({ type: actions.fetchSuccess, payload: res.data });
})
.catch((err) => {
setLoading(false);
setError(err.message);
dispatch({ type: actions.fetchFailure, payload: err.message });
});
}, [url]);

return { loading, error, data };
return state;
};

export default useFetch;

0 comments on commit 1c87bf5

Please sign in to comment.