27
loading...
This website collects cookies to deliver better user experience
const useTodos = () => {
const todos = useTodosStore()
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(null)
const fetchTodos = useCallback(async () => {
setIsLoading(true)
try {
const { data: todos } = await axios.get("/api/todos")
setTodos(todos)
setError(null)
} catch(e) {
setError(e)
}
setIsLoading(false)
})
useEffect(() => {
fetchTodos()
}, [fetchTodos])
return {
todos,
fetch: fetchTodos,
isLoading: false,
error: null
}
}
const App = () => {
const { todos, isLoading, error } = useTodos()
// other stuff
}
useToggleTodo
const useToggleTodos = () => {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(null)
const toggleTodo = useCallback(async todoId => {
setIsLoading(true)
try {
const { data } = await axios.get(`/api/todos/${todoId}/toggle`)
setError(null)
setIsLoading(false)
return data
} catch(e) {
setError(e)
}
setIsLoading(false)
})
return [toggleTodo, { isLoading, error }]
}
import { useQuery } from "react-query"
const fetchTodos = () => axios.get('/api/todos').then(res => res.data())
const useTodos() => {
const { data: todos, isLoading, error } = useQuery('todos', fetchTodos)
return { todos, isLoading, error }
}
useToggleTodo
we can use the useMutation from react-query
so that our to-dos query is re-fetched whenever we toggle a to-doimport { useMutation } from "react-query"
const getToggleTodoById = todoId => axios.get(`/api/todos/${todoId}/toggle`)
const useToggleTodo = () => {
return useMutation(getToggleTodoById, { refetchQueries: ["todos"] })
}
react-query
in seconds and didn't have to change more than a couple of lines. And now we have these nice hooks for our components to hooks into.