I am using React with Axios. I have a json file and trying to get the data passed to my React App.
$url is the url of the Json file and when I run console log I can see that the json data is getting logged, so think I am fetching the data correctly, but it does not seem to be assigning the data to my variables.
My console log shows like below
Array [ {…} ]
0: Object { title: "Page Title", body: "<p>Page body</p>", uri: "uri.jpg", … }
length: 1
This is my code
const PageDetails = () => {
const [page, setPage] = useState();
const [morePages, setMorePages] = useState();
const fetchPageDetails = () => {
axios({
url: $url,
method: 'get'
})
.then((response) => {
console.log(response.data)
setPage(response.data);
})
.catch((error) => {
console.log(error);
});
};
return (
<h1>{page[0]?.title}</h1>
<div>{page[0]?.body}</div>
);
};
However, I get error page is undefined.
How can I pass the json response? Thanks
2
Answers
No initial value is provided, so the default is
undefined
:You can provide an initial value of an empty array if you like:
Alternatively, you can modify the optional chaining to support an
undefined
value inpage
:How do you call the fetch function?
It seems you need to use useEffect to call it on initial render.
Also you need to set default state.