I have the following function component in React:
function GetData() {
const [randomDataJSON, setRandomDataJSON] = useState('');
const url = 'https://randomuser.me/api/';
const getData = () => {
axios
.get(`${url}`)
.then((results) => {
const userData = results.data.results;
setRandomDataJSON(JSON.stringify(userData, null, 2));
})
.catch((err) => console.error(err));
};
return (
<div>
<h3>GetData Component</h3>
<pre>{randomDataJSON[0].name.first}</pre>
<button onClick={getData}>Get Data</button>
</div>
);
}
export default GetData;
The JSON data from the API is as follow:
[
{
"gender": "female",
"name": {
"title": "Miss",
"first": "Barbara",
"last": "Sullivan"
},
...
I would like to access and display the first name of the JSON data from the API by using {randomDataJSON[0].name.first in the <pre> tag. However, I keep getting the following error message: TypeError: Cannot read properties of undefined (reading 'name')
useEffectthere.