Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
When I open the modal, the api call running always

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();
  }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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();
  }, []);
about 4 years ago · Juan Pablo Isaza Report

0

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]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!