Home > Mobile >  How to return value from an API call in javascript to a React component
How to return value from an API call in javascript to a React component

Time:10-28

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

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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.

CodePudding user response:

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.

  • Related