Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

javascript - How do I return data from multiple APIs to display on one page in React?

I have two API endpoints that I am retrieving data from and I want to display the number of records in each. This is my code so far, which sort of works, and test6tg5ing the API in Postman returns the correct data -

const [orders, setOrders] = useState([]);
useEffect(() => {
  const fetchData = async () => {
    const resSeven = await axios('http://localhost:5000/api/7daycheck');
    const resThirty = await axios('http://localhost:5000/api/30daycheck');
    setOrders({ seven: resSeven.data, thirty: resThirty.data });
    };
    fetchData();
}, []);
question from:https://stackoverflow.com/questions/65939152/how-do-i-return-data-from-multiple-apis-to-display-on-one-page-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The initial state of orders is an empty array:

const [orders, setOrders] = useState([]);

Which has no property called seven. So when you try to display that state:

<p>{orders.seven.length}</p>

You'll get an error. If the resulting value for orders isn't an array then you shouldn't set it to one to begin with. Give it the structure you expect:

const [orders, setOrders] = useState({ seven: [] });

This would initialize it to an object with a property called seven which itself is an empty array. Then the length will correctly be 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...