Skip to content

Instantly share code, notes, and snippets.

@sandeshdamkondwar
Last active June 21, 2023 17:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandeshdamkondwar/d1f2954dd290623f12021c667eb1871a to your computer and use it in GitHub Desktop.
Save sandeshdamkondwar/d1f2954dd290623f12021c667eb1871a to your computer and use it in GitHub Desktop.
Fetch data using useReducer
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