I am new in React js. I fetched one data from open api by using express server. I successfully browse the random cat text to my react component. Now I want to create a button which will fetch a new set of cat facts. While the frontend is fetching the data, it has to display a loading spinner in place of the results. When the results have been fetched, the spinner must be hidden and the results are rendered. If there are errors when fetching the data, the error message has to be logged with console.log.
This is my server which works perfectly.
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
const axios = require("axios");
const morgan = require("morgan");
const cors = require("cors");
app.use(morgan("common"));
app.use(cors());
app.get("/cat", async (req, res, next) => {
axios
.get("https://cat-fact.herokuapp.com/facts/random?animal_type=cat&amount=5")
.then(response => res.send(response.data))
.catch(err => {
console.log(err);
res.status(500).send(err);
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
This is my React component.
import React, { useEffect, useState } from "react";
const Home = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetchdata();
}, []);
const fetchdata = async () => {
const response = await fetch("http://localhost:5000/cat");
const data = await response.json();
console.log(data);
setData(data);
};
return (
<div className="bg-color">
{data.map(facts => {
return (
<ul>
<li>{facts.text}</li>
</ul>
);
})}
<button>new data</button> //IN HERE I WANT to FETCH NEW DATA and showing loading spinner.
</div>
);
};
export default Home;
Change your component like this:
import React, { useEffect, useState } from "react";
const Home = () => {
const [data, setData] = useState([]);
const [loadingData, setLoadingData] = useState(false);
useEffect(() => {
fetchdata();
}, []);
const fetchdata = async () => {
setLoadingData(true);
const response = await fetch("http://localhost:5000/cat");
const data = await response.json();
console.log(data);
setData(data);
setLoadingData(false);
};
return (
<div className="bg-color">
{data.map(facts => {
return (
<ul>
<li>{facts.text}</li>
</ul>
);
})}
{!loadingData && <button onClick={() => fetchdata()}>new data</button>}
{loadingData && <span>Loading...</span>}
</div>
);
};
export default Home;