Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!