Skip to content

Instantly share code, notes, and snippets.

@mark123jesper
Created October 4, 2021 00:02
Show Gist options
  • Save mark123jesper/7c26b6e71324bb694bb329f8d7aadba3 to your computer and use it in GitHub Desktop.
Save mark123jesper/7c26b6e71324bb694bb329f8d7aadba3 to your computer and use it in GitHub Desktop.
Use useReducer with fetch API
import React, { useEffect, useReducer } from 'react';
import axios from 'axios'
import './App.css';
const initialState = {
loading: true,
error: "",
todos: [],
};
const reducer = (state, action) => {
switch (action.type) {
case 'SET_DATA':
return {
loading: false,
error: "",
todos: action.payload,
}
case 'SET_ERROR':
return {
loading: false,
error: "There are some errors",
todos: [],
}
default:
return state;
}
}
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/todos")
.then(res => {
console.log(res.data)
dispatch({ type: 'SET_DATA', payload: res.data })
})
.catch(err => {
dispatch({ type: 'SET_ERROR' })
})
}, [])
const listmarkup = (
<ul>
{state.todos.map(todo => <li key={todo.id}>{todo.title}</li>)}
</ul>
)
return (
<div className="App">
{state.loading ? 'Loading' : (state.error ? state.error : listmarkup)}
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment