useEffect(() => {
const url = "https://api.adviceslip.com/advice";
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
} catch (error) {
console.log("error", error);
}
};
fetchData();
}, []);
// mycomponent.js
import React, { useEffect, useState} from 'react';
import axios from 'axios';
const MyComponent = () => {
const [loading, setLoading] = useState(true);
const [data, setData] = useState([])
useEffect(() => {
const fetchData = async () =>{
setLoading(true);
try {
const {data: response} = await axios.get('/stuff/to/fetch');
setData(response);
} catch (error) {
console.error(error.message);
}
setLoading(false);
}
fetchData();
}, []);
return (
<div>
{loading && <div>Loading</div>}
{!loading && (
<div>
<h2>Doing stuff with data</h2>
{data.map(item => (<span>{item.name}</span>))}
</div>
)}
</div>
)
}
export default MyComponent;
import {useEffect,useState} from 'react'
const App = () => {
const [data,setData] = useState([])
useEffect(()=>{
fetch('https://fakestoreapi.com/products').then(res => res.json()).then(data => {
setData(data);
}).catch(e=>console.log(e.message));
},[])
console.log(data);
return (
<div>
{data.map(i => <p key={i.id}>{i.title}</p> )}
</div>
)
}
export default App