I'm new to using Axios so I figured I would use it with React to make a small PWA just for fun and to learn it. The function is simple press button info get's displayed. When I'm trying to display the info in the return() i get an error saying it can't read the property of the api endpoint so I think what is happening is it's trying to render it before the function is being called. I assume this is a good use for async / await but I'm not sure how to implement it.
Here is the code
const IndexPage = () => {
const [data, getData] = useState([])
const options = {
method: 'GET',
url: 'https://dad-jokes.p.rapidapi.com/random/joke',
headers: {
'X-RapidAPI-Host': 'dad-jokes.p.rapidapi.com',
'X-RapidAPI-Key': '17fb7de893msh59a82cece7f697ap1c0305jsn0e7db5ca2d76'
}
};
function jokes() {
axios.request(options).then((res) => {
console.log(res.data);
const data = res.data
getData(data)
}).catch((error) => {
console.error(error);
});
}
return (
<Layout>
<main className="full-page">
<div className="center">
<cite>Press for the best dad jokes around!</cite>
<button onClick={jokes}> Get Jokes</button>
<h4>{data.body[0].setup}</h4> // this is running before function is being called onClick.
<p>{data.body[0].punchline}</p>
</div>
</main>
</Layout>
);
};
thank you in advance!
CodePudding user response:
const [data, getData] = useState([])
Should be called setData
. See https://reactjs.org/docs/hooks-state.html
On first run, data
is set to []
, an empty array. Later on,
<h4>{data.body[0].setup}</h4>
You try to read body[0].setup
from the array. This line is equivalent to [].body[0].setup
.
You can use the optional chaining operator (?.
) here:
<h4>{data?.body?.[0]?.setup}</h4>
Which will evaluate to undefined
instead of complaining "can't read property of undefined".