1

i tried to get the length of my Json response but it doesn't work i used "length" with my json result this is what i tried in my class in react js :

  componentDidMount() {
    axios.get(`http://localhost:51492/api/CommentSurExperience/GetAllCommentOfExperience/${this.props.passedVal}`)
      .then(res => {
        const persons = res.data;
        const longeur = res.length;
        this.setState({ persons, longeur });
      })
  }

then i returned this :

<div> <p> { this.state.longeur}</p> </div>

but i got an empty result .

how can i count how many elements in my JSON response , please thank you for your help.

**********update*********** this is my JSON result using postman enter image description here

and this is a capture showing what console.log(res) shows

enter image description here

15
  • 1
    Could you show a sample of what res looks like? Commented Aug 16, 2018 at 13:49
  • Looks like res is a json object and not an array Commented Aug 16, 2018 at 13:52
  • @ChrisR i updated my post with a capture of Json result Commented Aug 16, 2018 at 13:53
  • 1
    could you write here result of console.log(res) ? Commented Aug 16, 2018 at 13:54
  • 1
    thats a postman api call, can you console.log(res)? Commented Aug 16, 2018 at 13:55

3 Answers 3

10

it should be

const longeur = res.data.length;
Sign up to request clarification or add additional context in comments.

1 Comment

that made it work , i just forgot the "data" , thank you so much
3

You need to use res.data.length. You can see the response schema in Axios docs.

1 Comment

that made it work , i just forgot the "data" , thank you so much
-2

You have to specify which key in your state that number belongs to:

setState({
  persons: res.data,
  longeur: longeur
})

Else it might be because it's res.data.length that you want?

3 Comments

This notation this.setState({ persons, longeur }); specifies the key in an implicit way.
"res.data.length " made it work , i just forgot the "data" , thank you so much
Well, yes. But he has not really specified what his state variables are called.

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.