Reputation: 42
How can i pass props to React Child Component ? I got error:
TypeError: Cannot read property 'user_id' of null
child
D:/T97/React-Test/test/src/child.js:6
3 | const child = (props) => {
4 | const {user} = props;
5 | return (
> 6 | <div className="child">
7 | {user.user_id}
8 | </div>
9 | );
View compiled
When i replace user.user_id
in child.js by JSON.stringify(user)
, i got:
{"user_id":1,"password":"null","user_name":"User1","email":"[email protected]","avatar_url":"https://picsum.photos/300/300"}
API: ("http://localhost:5000/user/1")
{"user_id":1,"password":"null","user_name":"User1","email":"[email protected]","avatar_url":"https://picsum.photos/300/300"}
App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Child from './child';
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
const fetchData = async () => {
const result = await axios.get(
'http://localhost:5000/user/1',
);
setUser(result.data);
};
fetchData();
}, []);
return (
<div className="App">
<Child user={user}/>
</div>
);
}
export default App;
child.js
import React from 'react';
const child = (props) => {
const {user} = props;
return (
<div className="child">
{user.user_id}
</div>
);
};
export default child;
Upvotes: 2
Views: 216
Reputation: 11
The child component will complete it's first render before you get the response from your API call. In that case, your child component will receive 'user' object as null as it's the initial state is null because of this
const [user, setUser] = useState(null);
You can either set your initial set to an empty object like this
const [user, setUser] = useState({});
Or you can add one more condition in your child component
<div className="child">
{user && user.user_id}
</div>
Once you get the response from API, the user state will be updated and you'll get your desired output.
Here is the working example https://stackblitz.com/edit/react-eutbvw?file=src%2FApp.js
Upvotes: 0
Reputation: 1
For the first rendering the user is not yet available (it's null initially), after the axios request/response is done the user will be available and you could use in your components, but you have to add a conditional rendering when the user is null :
<div className="child">
{user && user.user_id}
</div>
Upvotes: 1