Home > front end >  unable to use await while doing multiple fetch requests
unable to use await while doing multiple fetch requests

Time:02-17

I am fetching data from an API. The first fetch URL i pass the data it returns success and the other fetch URL then using second fetch URL i fetch the data and print it. I was unable to use await as after doing a fetch request of the first URL its takes time for the second fetch URL to gets the data before calling it for the data so i was thinking to use await. The input is CC(C)(C)Br. Here is the code link

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";

async function App() {
  const [solutestate, setSolutestate] = useState("");
  const [fetchData, setFetchData] = useState("");
  const [jsondata, setjsonData] = useState("");
  console.log(solutestate);
  console.log(fetchData);

  let params = new URLSearchParams({
    solute: solutestate
  });

  const onSubmit = (e) => {
    e.preventDefault();
    let [res1, res2] = await Promise.all([
      fetch(
        `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_two?${params}`,
        {
          method: "GET"
        }
      ),
      fetch(
        `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_solubility_json`,
        {
          method: "GET"
        }
      )
    ]);
    setFetchData(res1);
    setjsonData(res2);
  };

  return (
    <div className="App">
      <>
        <form noValidate onSubmit={onSubmit}>
          <div>
            Input: CC(C)(C)Br
            <TextField
              label="Solute"
              variant="outlined"
              onChange={(e) => setSolutestate(e.target.value)}
            />
            <Button type="submit" variant="contained">
              Submit
            </Button>
            <TextField label="Result" variant="outlined" value={fetchData} />
            {jsondata}
          </div>
        </form>
      </>
    </div>
  );
}
export default App;

CodePudding user response:

The await keyword is only valid on places where asynchronous code is accepted.

The easiest here is to make the onSubmit funcion async.

const onSubmit = async (e) => {
    let [res1, res2] = await Promise.all([
        fetch(
            `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_two?${params}`,
            {
                method: "GET"
            }
        ),
        fetch(
            `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_solubility_json`,
            {
                method: "GET"
            }
        )
    ]);

// etc
}

CodePudding user response:

React components cannot be made async like this. What you probably want is to execute an async callback once the button is clicked.

const onSubmit = async (e) => {
    e.preventDefault();
    let [res1, res2] = await Promise.all([ /* ... */ ]);
    setFetchData(res1);
    setjsonData(res2);
}

If you don't want your handler function itself to be async, you can also just call a new async function:

const onSubmit = (e) => {
    e.preventDefault();
    const fetchData = async () => {
        let [res1, res2] = await Promise.all([ /* ... */ ]);
        setFetchData(res1);
        setjsonData(res2);
    }
    fetchData();
}
  • Related