2

I have following response that I get in fetch()

{
  "errorCode": "00",
  "errorMsg": "success",
  "roleList": [
    {
      "role_id": 900,
      "roleDescription": "Role_I"
    },
    {
      "role_id": 901,
      "roleDescription": "Role_II"
    }
  ]
}

Now i need to get roleDescription and render it in , So i tried traversing through the JSON and storing the roleDescription in an array in state.

below is the method written for the same:

getroles(e) {
          fetch('http://xyz', {
            method: 'POST',
            body: JSON.stringify({
              "role_id": this.props.location.state.role_id
            })
          })
          .then((response) => response.json())
            .then((responseJson) => {
              console.log(`response of getroles: `, responseJson)
              if (responseJson.errorCode === '00') {
                this.setState({roleList : JSON.stringify(responseJson.roleList)});
                let temp = [];
                for (var i=0; i < JSON.stringify(responseJson.roleList).length; i++) {
                  temp.push(JSON.stringify(responseJson.roleList[i].roleDescription))
              }
              }
              else {
               alert("Error Fetching roles" + responseJson.errorMsg);
              }

            })
            .catch((error) => {
             console.error(error);
            });
        }

but i am getting error

Cannot read property 'roleDescription' of undefined

on line temp.push

I am very new to react so I am not quite sure if I have the right approach. Please help.

6
  • Can you be more explicit? you need to push the roleDescription for each roleList in the temp array? Commented Feb 12, 2019 at 10:47
  • @Sabbin i need to display all the roleDescriptions in a dropdown. So I am trying to extract the roleDesciption from the JSON and store it in an array Commented Feb 12, 2019 at 10:55
  • I'll create a fiddle with a much simpler approach if the response below from Matei is not ok for you Commented Feb 12, 2019 at 10:59
  • yes,please... that would help.. Commented Feb 12, 2019 at 11:05
  • remove JSON.stringify. Because it making the array into a string and running up to its length. Use responseJson.roleList.length instead Commented Feb 12, 2019 at 11:07

2 Answers 2

3

You shouldn't use the JSON.stringify method at all:

getroles(e) {
    fetch('http://xyz', {
        method: 'POST',
        body: JSON.stringify({
          "role_id": this.props.location.state.role_id
        })
    })
    .then((response) => response.json())
    .then((responseJson) => {
        console.log(`response of getroles: `, responseJson)
        if (responseJson.errorCode === '00') {
            this.setState({roleList : responseJson.roleList});
            let temp = [];
            for (var i = 0; i < responseJson.roleList.length; i++) {
              temp.push(responseJson.roleList[i].roleDescription);
            }
        }
        else {
            alert("Error Fetching roles" + responseJson.errorMsg);
        }
    })
    .catch((error) => {
        console.error(error);
    });
}

I'm wondering why do you receive a list of roles if you query for a single role?

Also, if you decide to set the temp variable into the state, it would be better to set both variables temp and roleList in the same time.

Later edit: You don't need to set any temp variable in order to populate a selector with the description of the roles.

getroles(e) {
    fetch('http://xyz', {
        method: 'POST',
        body: JSON.stringify({
          "role_id": this.props.location.state.role_id
        })
    })
    .then((response) => response.json())
    .then((responseJson) => {
        if (responseJson.errorCode === '00') {
            this.setState({roleList : responseJson.roleList});
        }
        else {
            alert("Error Fetching roles" + responseJson.errorMsg);
        }
    })
    .catch((error) => {
        console.error(error);
    });
}

When you render the selector you should have something like:

<select onChange={(event) => alert('Role description for role having id ' + event.value + ' has been selected')}>
    <option value="">Please choose a description</option>
    {this.state.roleList.map((role) => {
         return (
              <option key={role.role_id} value={role.role_id}>
                  {role.roleDescription}
              </option>
         );
    })}
</select>
Sign up to request clarification or add additional context in comments.

5 Comments

i am getting a list of roles and i need to display the discriptions in a dropdown
map it over HTML component of dropdown. i.e this.state.roleList.map(/*return yourhtml component with values /*)
@Matei I got the roledescription in the temp[] but how to populate the dropdown?
use the map function inside the render method in your template
@ChandraniChatterjee just updated my answer to show you how to render the descriptions
1

This is show your function should look

getroles(e) {
    fetch('http://xyz', {
        method: 'POST',
        body: JSON.stringify({
          "role_id": this.props.location.state.role_id
        })
    })
    .then(async (response) => {
       const responseJson = await response.json();
       if (responseJson.errorCode === '00') {
          const roleList = responseJson.roleList.map((element) => element.roleDescription);
          this.setState({
             roleList
          });
       } else {
          alert("Error Fetching roles" + responseJson.errorMsg);
       }
    })
      .catch((error) => {
         console.error(error);
    });
}

Here is a working fiddle with the json fetched from an external source JsFiddle

or you can use it with 2 then if you like

getroles(e) {
    fetch('http://xyz', {
        method: 'POST',
        body: JSON.stringify({
          "role_id": this.props.location.state.role_id
        })
    })
    .then((response) => response.json())
    .then((response) => {
       if (responseJson.errorCode === '00') {
          const roleList = responseJson.roleList.map((element) => element.roleDescription);
          this.setState({
             roleList
          });
       } else {
          alert("Error Fetching roles" + responseJson.errorMsg);
       }
    })
      .catch((error) => {
         console.error(error);
    });
}

4 Comments

i got the roleDescriptions in the temp[] in my state with the help to @Matei but how to populate the dropdown? I am using the <select><option>{this.state.temp[0]}/</select> and this renders the first role in the dropdown.but how to bind all the roles from state to <select> ?
it should be <select>{this.state.temp.map((element)=>(<option>{element}</option>))}</select> this is if you have the temp set in the state
I've corrected the above comment, now it should be ok
You're welcome, you could use the map function for constructing your temp array, it's much cleaner and easy to read instead of the for

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.