0

am trying to display the first name of a user from a fetched api data... What could be wrong with this Reactjs code? i confirmed there was data already fetched from the api, but in displaying it... it returns blank and no errors

class App extends Component 
    constructor() {
      super()
      this.state = {
        loading: false,
        user: {}
      }
    }
    componentDidMount() {
      this.setState({loading: true})
      fetch("https://reqres.in/api/users/2")
      .then(response => response.json())
      .then(data => {
        this.setState({
          loading: false,
          user: data
        })
      })
    }
  render() {
    const text = this.state.loading ? "loading..." : this.state.user.first_name
    return (
      <div>first name: {text}</div>
    )
  }
}

export default App

6
  • what does data look like in .then(data => { Commented Oct 25, 2020 at 6:39
  • 1
    You can make this a bit less redundant if you make this to this.state = {loading: true} and then removing this.setState({loading: true}) in componentDidMount Commented Oct 25, 2020 at 6:41
  • {"data":{"id":2,"email":"[email protected]","first_name":"Janet","last_name":"Weaver","avatar":"s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"},"ad":{"company":"StatusCode Weekly","url":"statuscode.org/","text":"A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."}} Commented Oct 25, 2020 at 6:42
  • Try this way this.setState({ loading: false, user: data.data }) Commented Oct 25, 2020 at 6:43
  • 1
    This should help! In your example, data is not really the data but the result. My guess is that you can access the data in the result using data.items or data.data. (One of these should work) Commented Oct 25, 2020 at 6:49

1 Answer 1

1

You name the whole response data in the final then callback function. The response itself also contains another Object called data, to access that you should use data.data in your setState .

You might like to de-structure it like this in your callback:

fetch("https://reqres.in/api/users/2")
.then(response => response.json())
      .then({data} => {
        this.setState({
          loading: false,
          user: data
        })
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.