简体   繁体   中英

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>
  );
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM