Home > Back-end >  How to parse a property of a react object
How to parse a property of a react object

Time:11-26

I am working in react and have a resonse ( ReviewerService.getReviewers()) that returns an array of values:

0: {id: 1, firstName: 'John', lastName: 'Doe', email: '[email protected]', responses: '{"q1":"yes","q2":"no","q3":"yes","rating":4}'}

1: {id: 2, firstName: 'bob', lastName: 'jefferson', email: '[email protected]', responses: '{"q1":"bob","q2":"yes","q3":"yes","rating":5}'}.

If this.state = { reviewers: [] }.

How do i pass the response data into reviewers and parse the responses property at the same time? Therefore, then I can access these properties of the responses easily.

class ListReviewsComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      reviewers: [],
    };
  }

  async componentDidMount() {
    await ReviewerService.getReviewers().then((res) => {
      this.setState({ reviewers: res.data });
    });

  this.setState({ reviewers.responses: JSON.parse(this.state.reviewers.responses)}); // error
 
  }

CodePudding user response:

can this work

  async componentDidMount() {
    try {

       const res = await ReviewerService.getReviewers();

       // got the data
       const reviewers = res.data;

       // not parse the responses for each reviewer
       const mappedReviewers = reviewers?.map(reviewer => {
         try {

                const parsedResponses = JSON.parse(reviewer.responses)

                // do you need to convert parsedResponses to an array ??

               return {
                 ...reviewer,
                 responses: parsedResponses
               }
           } catch(error) {
                 return {
                 ...reviewer,
                 responses: [] //
               }
           }

         });
       
        this.setState({ reviewers: mappedReviewers})
    
      } catch (error) {
       // log errors
      } 
   }

  

Hope this helps you to sort out the issue

CodePudding user response:

I think that you array returned by

ReviewerService.getReviewers()

should be in json format, treated or parsed, before, setted in setState:

data = [ {id: 1, firstName: 'John', lastName: 'Doe', email: '[email protected]', responses: '{"q1":"yes","q2":"no","q3":"yes","rating":4}'}
        ,{id: 2, firstName: 'bob', lastName: 'jefferson', email: '[email protected]', responses: '{"q1":"bob","q2":"yes","q3":"yes","rating":5}'} ];

Then you do this, putting array in a json treated object format

async componentDidMount() {
await ReviewerService.getReviewers().then((res) => {
  this.setState({ reviewers: res.data });
});

When you do:

this.setState({ reviewers: res.data });

You area putting on this.state.reviewers, all list and all objects nested in.

You could access this.state on this component like this method below:

getResponsesOfReviewersOnArrayByIndex = (index) => {
    return this.state.reviewers[index].responses
}

Or just in some method access,

this.state.reviewers[i].firstName

You can try this to understand better the JSON parse function:

const reviewersData = '[{"name":"neymar"}, {"name":"junior"}]';
const reviewers = JSON.parse(reviewersData);

console.log(reviewers[0].name);

In this W3Schools to see more examples of JSON.parse()

Hope this helps.

  • Related