AutoFetching with custom Hook in React,
Table of contents
No headings in the article.
with useEffect,
import React, { useState,useEffect } from 'react';
import axios from 'axios'
// In given n seccond this should auto refresh
function useTodos(n){
const [todos, setTodods] = useState([])
const [loading, setLoading] = useState(true);
useEffect(()=>{
// simple, A function for calling an API
function getDataFetch(){
axios.get("https://sum-server.100xdevs.com/todos")
.then(res=>{
setTodods(res.data.todos)
setLoading(false)
})
}
// here , in every n seccond call the fetchAPI()
const value = setInterval(()=>{
getDataFetch()
},n*1000)
// this is for when the setInterval is running, should run atleat
getDataFetch()
// cleaning up the Interval , when two setInterval is running
return () => {
clearInterval(value)
}
// here is the dev dependcies , when n chaages, useEffect calls again
},[n])
return {todos,loading}
}
function App(){
// got the input value from function , and passed here
const {todos,loading} = useTodos(5)
return (
<div>
{loading?<div>loading..</div>:todos.map((eachTodo)=> <Track todo= {eachTodo}/>)}
</div>
)
}
function Track({todo}){
return <div>
{todo.id}<br/>
{todo.title}<br/>
{todo.description}<br/>
{todo.completed}<br/>
</div>
}
export default App