I'd like that if I click onto a link and the modal is open the api call runs one time. Unfortunately it's running always, till the open state is true.
const [open, setOpen] = useState(false);
const [content, setContent] = useState();
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
const fetchData = async (movieName) => {
console.log("Fetching");
const { data } = await axios.get(
`https://en.wikipedia.org/w/api.php?action=query&origin=*&list=search&utf8=1&formatversion=latest&srsearch="${movieName}" articletopic:films`
);
setContent(data);
console.log(data);
};
if (open) {
fetchData();
}
CodePudding user response:
You should use useEffect
hook to call the API only once when the component is mounted.
Replace below
if (open) {
fetchData();
}
with
import { useEffect } from "react";
...
...
useEffect(() => {
fetchData();
}, []);
CodePudding user response:
As you are directly calling fetchData
when open
is true. When api call is successful it setContent
. Which triggers component to re render. It agains call the api and sets state re-render and so on. Call api inside useEffect
.
useEffect(() => {
if (open) {
fetchData();
}
}, [open]);