I have js file which contains data that I am rendering on the page using useState. I have a button Display which uses fetch API to get more data and display below the existing data.
I would like to display Loading when Display button is clicked till data arrives.
Problem is whole page is re rendered with Loading. I would like to display data that I am getting from js file as it is and just display Loading below Display button till I get more data from API
const [isLoading, setIsLoading] = useState(false);
if (isLoading) {
return <h2>Loading..</h2>;
}
const fetchData = async () => {
setIsLoading(true);
const response = await fetch(fetchDataUrl);
const data = await response.json();
setIsLoading(false);
setMoreData(data.datas);
};
const Component = () => {
const [isLoading, setIsLoading] = useState(false);
const fetchData = () => {
setIsLoading(true)
fetch(someUrl)
.then(data => {
setData(data)
setIsLoading(false)
});
}
return (
<>
{yourData.map((data) => <IdkMaybeItsSomeComponent data={data}>}
{ isLoading
? <h2>Loading...</h2>
: <button onClick={fetchData}>Get More Data</button> }
</>
)
}
How about something like that? Only showing the loading at the bottom when you are currently loading data.