Skip to content

Instantly share code, notes, and snippets.

@abhishek2x
Created August 29, 2020 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhishek2x/97381ac60605aef33ebf99740b508877 to your computer and use it in GitHub Desktop.
Save abhishek2x/97381ac60605aef33ebf99740b508877 to your computer and use it in GitHub Desktop.
Using Axios and useReducer to fetch data in React
import React, { useReducer, useEffect } from "react";
import axios from "axios";
const initialState = {
loading: true,
error: "",
post: {},
};
const reducer = (state, action) => {
switch (action.type) {
case "FETCH_SUCCESS":
return {
loading: false,
post: action.payload,
error: "",
};
case "FETCH_ERROR":
return {
loading: false,
post: {},
error: "SOMETHING WENT WRONG",
};
default:
return state;
}
};
function DataFetching2() {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
axios
.get(`https://jsonplaceholder.typicode.com/posts/1`)
.then((res) => {
dispatch({ type: "FETCH_SUCCESS", payload: res.data });
})
.catch((err) => {
dispatch({ type: "FETCH_ERROR" });
});
}, []);
return (
<div>
{state.laoding ? "Loading..." : state.post.title}
{state.error ? state.error : null}
</div>
);
}
export default DataFetching2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment