3 - Data fetching hooks
Course: Custom Hooks - chapter 3
Data fetching hooks can be used to encapsulate all the logic to fetch the data from your backend
For example, look at the following code-
import { useEffect, useState } from 'react'import axios from 'axios'
function App() { const [todos, setTodos] = useState([])
useEffect(() => { axios.get("https://sum-server.100xdevs.com/todos") .then(res => { setTodos(res.data.todos); }) }, [])
return ( <> {todos.map(todo => <Track todo={todo} />)} </> )}
function Track({ todo }) { return <div> {todo.title} <br /> {todo.description} </div>}
export default App
Step 1 - Converting the data fetching bit to a custom hook
Section titled “Step 1 - Converting the data fetching bit to a custom hook”import { useEffect, useState } from 'react'import axios from 'axios'
function useTodos() { const [todos, setTodos] = useState([])
useEffect(() => { axios.get("https://sum-server.100xdevs.com/todos") .then(res => { setTodos(res.data.todos); }) }, [])
return todos;}
function App() { const todos = useTodos();
return ( <> {todos.map(todo => <Track todo={todo} />)} </> )}
function Track({ todo }) { return <div> {todo.title} <br /> {todo.description} </div>}
export default AppStep 2 - Cleaning the hook to include a loading parameter
Section titled “Step 2 - Cleaning the hook to include a loading parameter”What if you want to show a loader when the data is not yet fetched from the backend?
import { useEffect, useState } from 'react'import axios from 'axios'
function useTodos() { const [loading, setLoading] = useState(true); const [todos, setTodos] = useState([])
useEffect(() => { axios.get("https://sum-server.100xdevs.com/todos") .then(res => { setTodos(res.data.todos); setLoading(false); }) }, [])
return { todos: todos, loading: loading };}
function App() { const { todos, loading } = useTodos();
if (loading) { return <div> Loading... </div> }
return ( <> {todos.map(todo => <Track todo={todo} />)} </> )}
function Track({ todo }) { return <div> {todo.title} <br /> {todo.description} </div>}
export default AppStep 3 - Auto refreshing hook
Section titled “Step 3 - Auto refreshing hook”What if you want to keep polling the backend every n seconds? n needs to be passed in as an input to the hook
import { useEffect, useState } from 'react'import axios from 'axios'
function useTodos(n) { const [loading, setLoading] = useState(true); const [todos, setTodos] = useState([])
function getData() { axios.get("https://sum-server.100xdevs.com/todos") .then(res => { setTodos(res.data.todos); setLoading(false); }) }
useEffect(() => { setInterval(() => { getData(); }, n * 1000) getData(); }, [n])
return { todos: todos, loading: loading };}
function App() { const { todos, loading } = useTodos(5);
if (loading) { return <div> Loading... </div> }
return ( <> {todos.map(todo => <Track todo={todo} />)} </> )}
function Track({ todo }) { return <div> {todo.title} <br /> {todo.description} </div>}
export default AppFinal solution
import { useEffect, useState } from 'react'import axios from 'axios'
function useTodos(n) { const [todos, setTodos] = useState([]) const [loading, setLoading] = useState(true);
useEffect(() => { const value = setInterval(() => { axios.get("https://sum-server.100xdevs.com/todos") .then(res => { setTodos(res.data.todos); setLoading(false); }) }, n * 1000)
axios.get("https://sum-server.100xdevs.com/todos") .then(res => { setTodos(res.data.todos); setLoading(false); })
return () => { clearInterval(value) } }, [n])
return {todos, loading};}
function App() { const {todos, loading} = useTodos(10);
if (loading) { return <div> loading... </div> }
return ( <> {todos.map(todo => <Track todo={todo} />)} </> )}
function Track({ todo }) { return <div> {todo.title} <br /> {todo.description} </div>}
export default Appswr - React Hooks for Data Fetching
Section titled “swr - React Hooks for Data Fetching”swr is a popular React library that creates a lot of these hooks for you, and you can use it directly.
For example -
import useSWR from 'swr'
// const fetcher = (url) => fetch(url).then((res) => res.json());const fetcher = async function(url) { const data = await fetch(url); const json = await data.json(); return json;};
function Profile() { const { data, error, isLoading } = useSWR('https://sum-server.100xdevs.com/todos', fetcher)
if (error) return <div>failed to load</div> if (isLoading) return <div>loading...</div> return <div>hello, you have {data.todos.length} todos!</div>}