useEffect not working with multiple dropdowns in Semantic UI React

随声附和 提交于 2020-06-17 09:42:26

问题


I am using Semantic UI React. The following JS code does not work for me:

import React, { useState, useEffect } from "react";
import { Dropdown, Form, Button } from "semantic-ui-react";

export const MovieDropdown = () => {
  const [movie, setMovie] = useState("");
  const [person, setPerson] = useState("");
  const [movieOptions, setMovieOptions] = useState([]);
  const [personOptions, setPersonOptions] = useState([]);

  useEffect(() => {
    Promise.all([
      fetch("/people").then(res =>
        res.json()
      ),
      fetch("/movies").then(res =>
        res.json()
      )
    ])
      .then(([res1, res2]) => {
        console.log(res1, res2);
        var make_dd = (rec) => {
            rec.map(x => {
              return {'key': x.name, 'text': x.name, 'value': x.name}
            })
        }
        setPersonOptions(make_dd(res1))
        setMovieOptions(make_dd(res2))

      })
      .catch(err => {
        console.log(err);
      });
  });

  return (
    <Form>
      <Form.Field>
        <Dropdown
          placeholder="Select Movie"
          search
          selection
          options={movieOptions}
          onChange={(e, {value}) => setMovie(value)}
        />
      </Form.Field>
      <Form.Field>
        <Dropdown
          placeholder="Select Person"
          search
          selection
          options={personOptions}
          onChange={(e, {value}) => setPerson(value)}
        />
      </Form.Field>

    </Form>
  );
};
export default MovieDropdown;

Problem is that I lose the DB connection when running this component. I tried with MySQL and SQLite and it gives the same issue. How to solve this? Should I have 1 fetch per component? I thank you in advance.

Kind regards, Theo


回答1:


Well, I dont know about the DB Connetion, but the remmended way of calling api in useEffect is like this:

useEffect({
 // your code here only once
},[])

OR,

useEffect({
 // your code here will run whenever id changes
},[id])

Your useEffect will run on every render,which is not recommended time/ way to make api calls.



来源:https://stackoverflow.com/questions/62288497/useeffect-not-working-with-multiple-dropdowns-in-semantic-ui-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!