Custom hooks for fetch data
function MyComponent() {
const [todos, fetchTodos, setTodos] = useRequest({
service: MyService.getTodos
})
if (todos.fetching) {
return <h1>Loading...</h1>
}
if (todos.error) {
return <h1>Oops! Something was wrong</h1>
}
const handleDeleteTodo = (todoId) => {
const newTodos = todos.data.filter((todo) => todo.id !== todoId)
setTodos({ data: newTodos })
}
return (
<div>
<TodoList todos={todos.data} onDelete={handleDeleteTodo} />
<Button onClick={fetchTodos}>Refresh</Button>
</div>
)
}
MIT © moralesbang
This hook is created using create-react-hook.