\n
The code i used is the following:
\nimport React, {useState, useEffect} from 'react';\nimport logo from './logo.svg';\nimport './App.css';\n\nfunction App() {\n\n const [error, setError] = useState(null);\n const [isLoaded, setIsLoaded] = useState(false);\n const [items, setItems] = useState([]);\n\n useEffect(() => {\n fetch("http://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json")\n .then(res => res.json())\n .then(\n (result) => {\n setIsLoaded(true);\n \n setItems(result); \n },\n // Note: it's important to handle errors here\n // instead of a catch() block so that we don't swallow\n // exceptions from actual bugs in components.\n (error) => {\n setIsLoaded(true);\n setError(error);\n }\n )\n }, [])\n\n\n if (error) {\n return <div>Error: {error.message}</div>;\n } else if (!isLoaded) {\n return <div>Loading...</div>;\n } else {\n return (\n <ul>\n {console.log(items)}\n </ul>\n );\n }\n}\n\nexport default App;\n
\nAny help would be great.
\n","author":{"@type":"Person","name":"Dazeh"},"upvoteCount":0,"answerCount":2,"acceptedAnswer":null}}Reputation: 316
When following this documentation https://reactjs.org/docs/faq-ajax.html I run the code and if i console.log()
the items variable in the return statement. I get the following which causes issues because the first response is empty:
The code i used is the following:
import React, {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
useEffect(() => {
fetch("http://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{console.log(items)}
</ul>
);
}
}
export default App;
Any help would be great.
Upvotes: 0
Views: 1625
Reputation: 11
You can use a conditional to run your code only if result is not empty to avoid crashing.
if (result) {
//your code
}
Upvotes: 1
Reputation: 622
It's not 'first response is empty' issue. First console.log runs before the async code executes, when async code executes and you change your state, component rerenders and reruns the console.log with newly updated items that are now filled with data fetched from api.
Perhaps you should read a bit more about react component lifecycles :)
Upvotes: 2