0

I am trying to get values from my state and props in function. This function is fired under componentWillReceiveProps method. However when i try to console log my props and state values under that function i get 'undefined' as result. Is there something to do with my state not updating fast enough? Am i missing to pass props somewhere? Where could lay error and how could i get my function to handle correct values?

handleShow() function:

state = {
    training: {},
    isCreator: null
}

componentWillReceiveProps(newProps) {
console.log(newProps);
    if (newProps.token) {
        axios.defaults.headers = {
            "Content-Type": "application/json",
            Authorization: newProps.token
        }
        const trainingID = this.props.match.params.trainingID;
        axios.get(`http://127.0.0.1:8000/api/${trainingID}/`)
            .then(res => {
                this.setState({
                    training: res.data
                });
                console.log('treener', res.data.coach)
            })
            .catch(err => {console.log(err)})
        this.handleShow()
    } else{}

}

handleShow() {
    if(this.props.token == this.state.training.coach) {
        console.log('Props:', this.props.token);// value of undefined
        console.log('State.training', this.state.training.coach)// 
        this.setState({
            isCreator: true
        })
    }else{
        this.setState({
            isCreator: null
        })
    }
}
Austin Roose
  • 69
  • 2
  • 11
  • I don't know y props token not working maybe component not re-rendered check u receive props console. Log(this.props) and in componentWillReceiveProps the function handleshow u can pass newprops token in that way u can check condition with token and state handleshow (newprops.token). . Finally check parent component for props – ikmo Aug 29 '20 at 17:07
  • Maybe you can try to use "componentDidUpdate" instead. – Pablo Darde Aug 29 '20 at 17:13
  • `componentWillReceiveProps` is unsafe (it won't work in React v17). Are you sure that the component receives some props? – marzelin Aug 29 '20 at 17:13
  • yes, when i console log 'res.data' under axios.get, i get correct results. This means that my props are correct, but somehow i cant access them under my function. – Austin Roose Aug 29 '20 at 17:32
  • @marzelin, it is strange because when i reaload page, props aare correct in function – Austin Roose Aug 29 '20 at 19:07

0 Answers0