Created
April 4, 2023 21:02
-
-
Save iamhaiderkhan/efdf071c133108b465e1f00a398b18b0 to your computer and use it in GitHub Desktop.
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, { useEffect, useState } from 'react'; | |
import useFetch from 'use-http' | |
function UseHTTPExample() { | |
const [todos, setTodos] = useState([]) | |
const { get, post, response, loading, error } = useFetch('https://jsonplaceholder.typicode.com') | |
useEffect(() => { initializeTodos() }, []); | |
async function initializeTodos() { | |
const initialTodos = await get('/todos') | |
if (response.ok) setTodos(initialTodos) | |
} | |
async function addTodo() { | |
const newTodo = await post('/todos', { title: 'iamhaiderkhan' }) | |
if (response.ok) setTodos([newTodo, ...todos]) | |
} | |
return ( | |
<> | |
<button onClick={addTodo}>Add Todo</button> | |
{error && 'Error!'} | |
{loading && 'Loading...'} | |
{todos.map(todo => ( | |
<div key={todo.id}>{todo.title}</div> | |
))} | |
</> | |
) | |
} | |
export default UseHTTPExample; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment