Last active
June 21, 2023 17:16
-
-
Save sandeshdamkondwar/d1f2954dd290623f12021c667eb1871a to your computer and use it in GitHub Desktop.
Fetch data using useReducer
This file contains hidden or 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 DataFetchingTwo() { | |
const [state, dispatch] = useReducer(reducer, initialState) | |
useEffect(() => { | |
axios | |
.get(`https://jsonplaceholder.typicode.com/posts/1`) | |
.then(response => { | |
dispatch({ type: 'FETCH_SUCCESS', payload: response.data }) | |
}) | |
.catch(error => { | |
dispatch({ type: 'FETCH_ERROR' }) | |
}) | |
}, []) | |
return ( | |
<div> | |
{state.loading ? 'Loading' : state.post.title} | |
{state.error ? state.error : null} | |
</div> | |
) | |
} | |
export default DataFetchingTwo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment