JSON
This is how the json object looks in state.
{
"gender": "male",
"name": {
"title":"Mr."
"first":"Mike",
"last": "Wazowski"
},
...
}
The React
const App = () => {
const [user, setUser] = React.useState([]);
React.useEffect(() => {
axios
.get("https://randomuser.me/api")
.then((response) => {
const info = response.data.results[0];
setUser(info);
})
.catch((err) => {
console.log(err);
});
}, []);
Accessing the first lvl data works fine
return (
<div>
<h1>Hello, {user.gender}</h1>
<h1>Hello, {user.email}</h1>
</div>
)
Calling object returns Err: Objects are not valid as a React child
return (
<div>
<h1>Hello, {user.name}</h1>
</div>
)
Calling nested data returns TypeError: user.name undefined error
return (
<div>
<h1>Hello, {user.name.first}</h1>
</div>
)
Why can I can access 'first level' data like gender, but not 'second-level' data like name.first?
Do I need some special syntax I'm unaware of?
{user['name']['first']}. I think it understands name andfirstas variables?axiosthings... Check the content ofresponse.data/response.data.results. If it's a string you might have to parse it first