user11733988
user11733988

Reputation:

I can console log my state but I still get "Cannot read property 'data' of undefined". Why?

I a trying to render a piece of text if my user status is true.


{this.state.userStatus.data == "true" && <div><p>aasdasdasdasdsdasd</p></div>}

However I get the error Cannot read property 'data' of undefined

The strange thing is that, if I omit the piece of code above, I can console log my userstatus and it says "true".

  componentDidMount() {
    this.getJobs();
    console.log
    this.getPeople();
    this.getUserStatus();
        return axios ({
            method: 'get',
            url: '/user',
            params: {},
            withCredentials: true
        }).then(result => {
          this.setState({ user: result.data }, () => {
            console.log("state in componentDidmount?", this.state.userStatus.data)
          });
        });
  }

  getUserStatus() {
    console.log("getuser status called")
    axios.get("/getUserStatus").then(result => {
      console.log("where my state at", this.state)
      this.setState({ userStatus: result.data }, () => {
          console.log("user status in getUserStatus(): ", this.state.userStatus.data)
   });
   });
}


Whats happening?

Upvotes: 0

Views: 71

Answers (4)

Mohammed Al-Reai
Mohammed Al-Reai

Reputation: 2786

at the first try to check the value of state by using console.log(this.state.userStatus) and show what the value and show it is updated and it found or not and check if this .state.userStatus if found the check the this .state.userStatus.data ==" true" that right if it noot found the condition false it will not show the text because you used and operation the first condition not true then not show the text

Upvotes: 0

Rebai Ahmed
Rebai Ahmed

Reputation: 1600

Try to initialize your state

constructor(props) {
            super(props);
            this.state = {userStatus: {}};
        }

Upvotes: 0

Jacob Nelson
Jacob Nelson

Reputation: 2466

extend your condition to

{this.state.userStatus && this.state.userStatus.data == "true" && <div><p>aasdasdasdasdsdasd</p></div>}

Upvotes: 1

Jason Goemaat
Jason Goemaat

Reputation: 29194

state.userStatus is undefined until the call returns.

Upvotes: 0

Related Questions