Suppose we want to load data when a page loads in React. Here is how to go about it:
Using Fetch
Using Promises
const loadData = useCallback(
() => {
const fetchData = fetch('MYURL').then(response => response.json()).then(data => {return data});
return fetchData;
},
[],
)
useEffect(() => {
let dataLoaded = true;
const reloadData = () => {
loadData().then(response => dataLoaded ? setData(response) : setData({}));
}
reloadData();
//Clean up function
return () => {
dataLoaded = false;
}
}, [loadData]);
Using async/await
const loadData = useCallback(
async () => {
const animals = await fetch('MYURL');
const data = await animals.json();
const result = data;
return result;
},
[],
);
useEffect(() => {
let dataLoaded = true;
const reloadData = async() => {
const fetchData = await loadData();
if(dataLoaded) {
setData(fetchData);
}
}
reloadData();
//Clean up function
return () => {
dataLoaded = false;
}
}, [loadData]);
Using Axios
Using Promises
const MyComponent = () => {
const [data, setData] = useState({});
const loadData = useCallback(() => {
const fetchData = axios.get('MYURL').then(response => {return response.data;});
return fetchData;
}, []);
useEffect(() => {
let dataLoaded = true;
const reloadData = () => {
if(dataLoaded) {
loadData().then(response => setData(response));
}
}
reloadData();
//Clean up function
return () => {
dataLoaded = false;
}
}, [loadData]);
}
Using async/await
const MyComponent = () => {
const [data, setData] = useState({});
const loadData = useCallback( async() => {
const fetchData = await axios.get('MYURL');
const result = await fetchData.data;
return result;
}, []);
useEffect(() => {
let dataLoaded = true;
const reloadData = async() => {
const fetchData = await loadData();
if(dataLoaded) {
setData(fetchData);
}
}
reloadData();
//Clean up function
return () => {
dataLoaded = false;
}
}, [loadData]);
}