0

I am confused as how to get a value of an item from a data returned by axios function. I've looked at many examples, but only avail are returning value using map, such as below.

render() {
  var student = this.state.student;
  return (
    student.map( d => (
      ..
      <td>{d.grade}
      ..
  );
)

But what I'm trying to do is store the value in a variable for manipulation. For example below, I want to extract the student grade:

class Student extends Component {
  state = { student: [], };
  
  componentDidMount() {
    axio.get(window.$API_URL).then(res=>this.setState({stduent: res.data}));
    var student = this.state.student;
    var grade = student.grade;                       //** doesn't work
    var grade = this.getGrade(student);              //** doesn't work
    var grade = getPropertyValue(student, "grade");  //** doesn't work
    ....
  }

  getGrade(student) {
    student.map(d=>{return(d.grade)});
  }

  getPropertyValue(obj, dataToRetrieve) {
    return dataToRetrieve
      .split('.')
      .reduce(function(o, k) {
        return o && o[k];
      }, obj)
  }

  render() { ....  }
}
itchibahn
  • 79
  • 2
  • 8
  • I've added a second link at the top of your post that might help. – Phil Dec 12 '22 at 00:18
  • I've looked at those links, but they're not what I'm asking for... – itchibahn Dec 12 '22 at 00:32
  • I beg to differ. Your first problem is that the Axios request is async so your state won't be updated until it resolves (first link). Secondly, you should only try and compute `student`, `grade`, etc after your state has been updated. If you were using function components, I'd say to use a [memo hook](https://reactjs.org/docs/hooks-reference.html#usememo) but since you're using classes, see the second link – Phil Dec 12 '22 at 00:36
  • FYI, you also have a typo... `stduent` should be `student` – Phil Dec 12 '22 at 00:55
  • 1
    So my state wasn't getting updated, I think I understand it now. I tried computing in render() and it works. Thank you. – itchibahn Dec 12 '22 at 02:02

0 Answers0