pythonreactjsfetch-apiconditional-rendering

how can we use two fetch requests at a time


I am trying to do a prediction on a model using a rest API and show the output on frontend using react.

If the prediction is 1 then I need to display the second prediction using conditional rendering. when I was trying to use two fetch request at a time it is not work. how to do it

  const [solutestate, setSoluteState] = useState("");
  const [solventstate, setSolventState] = useState("");
  const [textstate, settextstate] = useState("");
  const [fetchData, setFetchData] = useState("");
  const [fetchDatatwo, setFetchDatatwo] = useState("");

  const [Error, setError] = useState(null);

  const onSubmit = (e) => {
    e.preventDefault(); // <-- prevent the default form action

    const formData = new FormData();
    formData.set("text_input", textstate); // <-- local component state
    console.log({ textstate });

    const formDatatwo = new FormData();
    formDatatwo.set("solute", solutestate); // <-- local component state
    formDatatwo.set("solvent", solventstate);

    fetch("http://127.0.0.1:3000/predict", {
      method: "post",
      body: formData,
    })
      .then((res) => res.json())
      .then((result) => {
        setFetchData(result.result);
      })
      .catch((err) => {
        setError(err.error);
        console.log(err);
      });

    fetch("https://flask-api-test1.herokuapp.com/predict", {
      method: "post",
      body: formDatatwo,
    })
      .then((res) => res.json())
      .then((result) => {
        setFetchData(result.result.predictions);
      })
      .catch((err) => {
        setError(err.error);
        console.log(err);
      });
  };

Solution

  • You can use Promise.all method for fetch multi api in a same time.

    const firstFetch = await fetch('firstUrl');
    const secondFetch = await fetch('secondUrl');
    
    const [firstResponse, secondResponse] = Promise.all([firstFetch, secondFetch])