最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - How to return value from an API call in javascript to a React component - Stack Overflow

programmeradmin0浏览0评论

I cant seem to return the value of this API call in javascript to my react ponent. 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 ponent, 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 ponent

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

I cant seem to return the value of this API call in javascript to my react ponent. 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 ponent, 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 ponent

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

Share Improve this question edited Mar 17, 2022 at 8:35 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Oct 28, 2021 at 11:41 lungulungu 872 silver badges10 bronze badges 1
  • the API calls are asyncronous. To get value you should use .then on the Promise. So it'll be ordersData().then(payload => console.log(payload)). Also you should return fetch from ordersData function. – bazzas Commented Oct 28, 2021 at 11:46
Add a ment  | 

3 Answers 3

Reset to default 5

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./ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Cleanest way I found was this

Change parent ponent 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 ponent 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 ponent and can set states from there instead.

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.

发布评论

评论列表(0)

  1. 暂无评论