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

131
Visualizações
How to return value from an API call in javascript to a React component

I cant seem to return the value of this API call in javascript to my react component. I have a java script file that calls an API. In the js file, results are returned but when I call the js function in useEffect in my react component, it returns undefined.

export function ordersData() {

    const partner_code = localStorage.getItem('partner_code')

    let items = []
    let data = []
    let isLoaded = false
    let error = ''

    fetch('xxxxxxxxxxxx' + process.env.REACT_API)
        .then(res => res.json())
        .then((result) => {
            for (let instance in result['docs']) {
                let payload = (result['docs'][instance])

                payload.id = instance

                payload.timestamp = shortMonthYear(payload.timestamp)

                data.push(payload)
            }

            items = data.reverse()

        }, (err) => {
            isLoaded(true)
            error(err)
        })
}

Here is my rect component

export default function OrdersChart() {

const [payload, setPayload]  = useState([])
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);

useEffect(() => {
    setPayload = ordersData()
    console.log(payload)
}, [])

........

The variable payload is empty

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to use React hooks for API calls and store the data. You can use useEffect hooks to call the API and use useState for storing data in the state.

const { useState } = React;

function useFetchData() {
  const [loading, setLoading] = React.useState([]);
  const [data, setData] = React.useState([]);

  React.useEffect(() => {
    setLoading(true);
    fetch("https://randomuser.me/api/?results=10")
      .then((response) => response.json())
      .then((responseJson) => {
        setData(responseJson.results);
        setLoading(false);
      })
      .catch((error) => {
        console.error(error);
        setLoading(false);
      });
  }, []);

  return { loading, data };
}

function App() {
  const { loading, data } = useFetchData();
   
  if(loading){
   return <p>Loading... </p>
  }

  return (
    <div>
      {data.map((item) => (
        <div>{item.name.first}</div>
      ))}
    </div>
  );

}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Cleanest way I found was this

Change parent component to this

useEffect(() => {
   newFunctionName();
}, [])

async function newFunctionName(){
   const response = await ordersData();
   console.log(response)
   // you can then set all your states directly in here
}

Change api call component to this.

export default async function ordersData() {
    try{
        const res = await fetch('xxxxxxxxxxxx' + process.env.REACT_API)
        return res
    } catch(err){
      console.log(err)
      return(err)
    }
}

Now you have the response in the parent component and can set states from there instead.

about 4 years ago · Juan Pablo Isaza Relatório

0

You dont return anything in this function. You just push payload value in data, that a local variable. You can use state and set value by setState.

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