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

277
Views
How to properly Populate a Dropdown with SQL Query Values in React.Js Hook

I have a react component called Sidebar.jsx. Within it, I am making an API call to get a array of fleets to populate an eventual JSX dropdown element within my Sidebar. This results in a simple JSON array.

I have imported a function called getFleets() from my services folder to make the API call. The service uses the fetch API to make a query call to my backend and looks like this:

export async function getFleets() {
    const resp = await fetch("http://localhost:5000/fleets", {
        method: 'GET',
        headers: {},
        mode: 'cors'
    });
    return resp.json();
};

However, when I use the website, it appears to infinitely make the API call. This is my first time trying to make an API call within a react component so I am a bit confused here. Other guides I've read online seem to be similar but I am obviously missing something.

What can I do to make this API call only once and retrieve my JSON array such that I can later use it to populate the options in my return ?

Sidebar.jsx

import React, { useEffect, useState } from "react";
import { getFleets } from "../services/FleetService";

const Sidebar = () => {
  const [data, setData] = useState([]);

  useEffect(() => {

    const setFleets = async () => {
        const fleets = await getFleets();
        console.log(fleets);
        setData(fleets);
      }
    setFleets();
  }, [data]);


  return (
    <>
    // Add data to <select> </select>
  );
};

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The way your code works, since data is part of the dependency array sent to useEffect, every time data changes the effect runs, which changes data, which runs the effect again ...resulting in the infinite loop.

The simple fix is to remove data from the dependency array, and explicitly specifying an empty array [] as the second parameter of useEffect. This will make the effect run only exactly once, when the component is first rendered.

You need to explicitly specify an empty array because when the second parameter isn't specified at all, the effect will run on every render, bringing back the infinite loop issue.

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!