-1

Why my values under this.props and this.state are undefined in my componentDidMount method? In other parts of my class component I can access my props and state values correctly. Do I need to pass them separately to somewhere or where have I made any mistakes?

There I get no values:

componentDidMount() {
    console.log(this.props.token)
    console.log(this.state.training.coach)
    // values are null and undefined.
    if (this.props.token == this.state.training.coach) {
        this.setState({
            iscreator: true
        });
        console.log(this.state.iscreator)
    } else {
        this.setState({
            iscreator: false
        });
    }
}

There I get correct values when accessing this.props.token:

handleDelete = (event) => {
    if (this.props.token !== null) {
        const trainingID = this.props.match.params.trainingID;
        axios.defaults.headers = {
                "Content-Type": "application/json",
                Authorization: this.props.token
            }
        axios.delete(`http://127.0.0.1:8000/api/${trainingID}/`)
        this.props.history.push('/');
        this.forceUpdate();
    } else {
    
    }
}
Tommy
  • 2,355
  • 1
  • 19
  • 48
Austin Roose
  • 69
  • 2
  • 11

1 Answers1

0

this.setState is asynchronous, meaning that the function after doesn't wait till it is complete so if you console.log your state right after updating it may still have the old value.

To fix this you can check your state value in your render where it will eventually update, or you can run a setState with a callback like this

this.setState({iscreator: true}, () => console.log(this.state.iscreator) )

This makes sure to run the console.log only after the setState is done.

Shmili Breuer
  • 3,927
  • 2
  • 17
  • 26
  • yes, but why are my this.props.token and this.state.training.coach values undefined? – Austin Roose Aug 26 '20 at 16:19
  • Cause it only takes a fraction of time for it to update and by the time you click on the button that calls `handleDelete` the `setState` has already been completed. – Shmili Breuer Aug 26 '20 at 16:51
  • But when i console those values above setState, they should have something in them. Why are those empty? Or what should i do in order it to work? – Austin Roose Aug 26 '20 at 20:08