Created
August 29, 2020 08:46
-
-
Save abhishek2x/97381ac60605aef33ebf99740b508877 to your computer and use it in GitHub Desktop.
Using Axios and useReducer to fetch data in React
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, { 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