Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

101
Visualizações
unable to use await while doing multiple fetch requests

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;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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();
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda