4

I have a object saved in state here is what is looks like when console.logged.

[{…}]
0:
NameOfUser: "James"
QuestionStatus: "Complete                      "
Date: (2) ["2020-03-10T14:13:45.257Z", "2020-03-10T14:13:45.257Z"]
AssignedWorkstation: "hello"
Email: "James@gmail.com"
ContactNumber: "12345678987654321"
__proto__: Object
length: 1
__proto__: Array(0)

to console log this I have just done this

console.log(this.state.WSAHeader);

How would I access the individual properties of this object.

I have tried

console.log(this.state.WSAHeader.NameOfUser);

This says it is undefined. How would I just access for example the NameOfUser property from this object stored in state.

I have also tried

console.log(this.state.WSAHeader[0].NameOfUser);

I am just looking for a suggestion for what is going wrong.

whole class


class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      answeredQuestions: [],
      WSAHeader: []
    };
    this.getWSAAnsweredQuestions = this.getWSAAnsweredQuestions.bind(this);
    this.getWSAHeader = this.getWSAHeader.bind(this);
  }

  getWSAAnsweredQuestions() {
    let data = {
      WSAId: this.props.location.state.WSAId
    };
    fetch("/get-completed-questions", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(recordset => recordset.json())
      .then(results => {
        this.setState({ answeredQuestions: results.recordset });
        console.log(this.state.answeredQuestions);
      });
  }

  getWSAHeader() {
    let data = {
      WSAId: this.props.location.state.WSAId
    };
    fetch("/get-WSA-header", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(recordset => recordset.json())
      .then(results => {
        this.setState({ WSAHeader: results.recordset });
        console.log(this.state.WSAHeader);
      });
  }

  componentDidMount() {
    this.getWSAHeader();
    this.getWSAAnsweredQuestions();
  }
  render() {
    // alert(this.state.WSAHeader.NameOfUser);
    console.log(this.state.WSAHeader);
    console.log(this.state.WSAHeader[0].NameOfUser);
    console.log(this.state.WSAHeader.QuestionStatus);

    return (
      <>
        <Header />
        {/* <h3 style={{ textAlign: "center" }}>Workstation Assessment</h3> */}

        <DisplayWSAHeader WSAHeader={this.state.WSAHeader} />
        <WSAAnsweredQuestions
          WSAHeader={this.state.WSAHeader.AssignedWorkstation}
          answeredQuestions={this.state.answeredQuestions}
          amountOfQuestions={this.state.answeredQuestions.length}
        />
      </>
    );
  }
}
henry pf
  • 300
  • 1
  • 5
  • 16
  • 1
    What did this one `console.log(this.state.WSAHeader[0].NameOfUser);` do? The example is formatted a little strange in the question, but that seems to be the correct way. – Brian Thompson Mar 10 '20 at 15:08
  • Cannot read property 'NameOfUser' of undefined – henry pf Mar 10 '20 at 15:10
  • Thats the error it logged – henry pf Mar 10 '20 at 15:10
  • 1
    Could you add the full object to the question? – Tamas Szoke Mar 10 '20 at 15:11
  • This code looks fine; there might be problem in `this` binding – Mechanic Mar 10 '20 at 15:11
  • Have edited the question for the whole class – henry pf Mar 10 '20 at 15:12
  • 2
    It's possibly not defined at the time of `console.log`. Before you expand the array in the object, what does it look like? Does it say `length: 0` then only when you expand it does it say `length: 1`? – Shaun E. Tobias Mar 10 '20 at 15:12
  • @ShaunE.Tobias is correct, you are loading that data after the component mounts, so it will be an empty array for at least the first render. You'll need to check its existence before accessing a property. – Brian Thompson Mar 10 '20 at 15:14
  • Once you can verify that the array is populated, `console.log(this.state.WSAHeader[0].NameOfUser)` is the correct syntax. – Brian Thompson Mar 10 '20 at 15:16
  • @BrianThompson you are correct. I made a button to test. ``` ``` – henry pf Mar 10 '20 at 15:18
  • 1
    that displayed the information I wanted so thanks guys ! If someone would like to post a answer stating this I am happy to accept :) – henry pf Mar 10 '20 at 15:19
  • Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – Emile Bergeron Mar 10 '20 at 15:37
  • Also see: [Can't access object property, even though it shows up in a console log](https://stackoverflow.com/q/17546953/1218980) – Emile Bergeron Mar 10 '20 at 15:38

1 Answers1

1

Answer from the question's comments

It's not defined at the time of console.log. This is true if before you expand the array in the console, it says length: 0 but then when you expand it, it says length: 1.

This is because you're loading the data after the component mounts so it will be empty the first time around. If you check that the array has been populated first before accessing it, it will work.

Shaun E. Tobias
  • 527
  • 3
  • 13