Reputation: 59
may parent is APP.JS and child is Dasboard.js im trying to pass user id from App.js to my child dashboard.js problem is i can only get the props on render but at the componentDidmount i cannot access it anymore how this this possible? can explain or give me link to read why this thing happen i thought that if u pass the props from parent child can receive it , with this case only work in render not in componentDidMount example below
App.js Code
class App extends Component {
constructor(props) {
super(props)
this.state = {
success:null,
results:'',
}
this.CheckLoginStatus = this.CheckLoginStatus.bind(this)
}
componentDidMount(){
this.CheckLoginStatus()
}
CheckLoginStatus(){
const token = localStorage.getItem('token');
const bearer = "Bearer"
if(token === null){
this.setState({success:false})
}
axios.get('http://127.0.0.1:8000/api/details',{
headers:{
Authorization:bearer+ ' ' +token
}
})
.then(response => {
if(response.status === 200){
this.setState({success:true,results:response.data.success})
}
}).catch(err => {
localStorage.clear()
})
}
render() {
return (
<Router>
<Switch>
<Route path="/login" exact component={Login} />
<Layout>
<Route path="/dashboard" exact render={props => (
<Dashboard {...props} status={this.state.success} results={this.state.results} />
)}
/>
</Layout>
</Switch>
</Router>
)
}
}
export default App
Upvotes: 1
Views: 55
Reputation: 10569
You should use componentDidUpdate
lifecycle, as in the initials render the result state
will be empty. You are getting the result data in app.js
componnetdidMount
lifecycle.
And when the dashboard mounts the first time, data of result will be empty.
Upvotes: 1
Reputation: 181
try:
componentDidMount(){
this.CheckLoginStatus()
}
CheckLoginStatus = async () => {
const token = localStorage.getItem('token');
const bearer = "Bearer"
if(token === null){
this.setState({success:false})
}
await axios.get('http://127.0.0.1:8000/api/details',{
headers:{
Authorization:bearer+ ' ' +token
}
})
.then(response => {
if(response.status === 200){
this.setState({success:true,results:response.data.success})
}
}).catch(err => {
localStorage.clear()
})
}
Upvotes: 0