This is a simple app in react that fetch the data from the nasa api.Div tag is re rendering continuously (like infinite loop) is there be any method to stop the api fetching after a promise is fulfilled.Also my arr is changing its value. . Thanks in advance.
function App() {
const [arr, setarr] = useState([]);
var promise = new Promise(async(resolve, reject) => {
axios
.get(
"https://api.nasa.gov/planetary/apod?api_key=R4s5xcOxoYklREakJOSoeNMCOK4tpM8iqg6slJ15&count=2&hd=true"
)
.then((res) => {
//res.data[i].hdurl
resolve(res.data);
});
return promise;
});
let show = () => {
promise.then((result) => {
setarr(result);
});
};
//show();
return (
<>
<div className="container">
{arr.map((val, i) => {
return (
<div
id="carouselExampleIndicators"
className="carousel slide"
data-bs-ride="carousel"
>
<div className="carousel-indicators"></div>
<div className="carousel-inner">
<div className="carousel-item active">
<img
src={val.hdurl}
key={i}
className="d-block w-100"
alt="img"
></img>
<br />
</div>
</div>
</div>
);
})}
</div>
</>
);
}
export default App;
CodePudding user response:
You need to put API requests under useEffect hook. The empty dependency array at the end means that the hook will only trigger once when the component is first rendered. Here's the code:
import { useEffect } from "react";
const App = () => {
const [arr, setArr] = useState([]);
useEffect(() => {
axios
.get(
"https://api.nasa.gov/planetary/apod?api_key=R4s5xcOxoYklREakJOSoeNMCOK4tpM8iqg6slJ15&count=2&hd=true"
)
.then((res) => {
setArr(res.data);
});
}, []);
return (
<>
<div className="container">
{arr.map((val, index) => {
return (
<div
id="carouselExampleIndicators"
className="carousel slide"
data-bs-ride="carousel"
key={index}
>
<div className="carousel-indicators"></div>
<div className="carousel-inner">
<div className="carousel-item active">
<img
src={val.hdurl}
className="d-block w-100"
alt="img"
></img>
<br />
</div>
</div>
</div>
);
})}
</div>
</>
);
};
export default App;