Skip to content

Instantly share code, notes, and snippets.

@iamhaiderkhan
Created April 4, 2023 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamhaiderkhan/efdf071c133108b465e1f00a398b18b0 to your computer and use it in GitHub Desktop.
Save iamhaiderkhan/efdf071c133108b465e1f00a398b18b0 to your computer and use it in GitHub Desktop.
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