1

I have places in my React Application that makes Axios calls and displays the data just fine.

However, I wanted a for loop, and I found code answer on stackover, but it is 3 years old, so I'm wondering if something changed.

  1. I am using webApi in place of Axios - it is an alias and i'm using elsewhere in the application for the path to server, also the call with console.log(.. is working displaying an array.
  2. I am wondering about the structure of the .get / .then with function(event) I don't do that in other calls to web api
  3. Could there be an issue with the state, or the const in the render() ? like something occurred already and html table stays blank?

This is my call to retrieve data and console.log shows the data fine.

webApi.get(`clinical/offlinemembers/${id}`)
        .then(function(event){
            console.log("event.data", event.data);
            th.setState({
                data: event.data
            });
        });

Then in the full code I will paste below, notice the const {contents} I would love it if this style of code works.

Here is the complete .js code

import React from 'react';
import webApi from './api/webApi';
import { withRouter, Route, Link, BrowserRouter as Router, Switch } from 'react-router-dom'
import queryString from 'query-string';
//import ActivateAccount from './ActivateAccount';


function getQueryVariable(variable)
{
        var query = window.location.search.substring(1);
        console.log(query)//"app=article&act=news_content&aid=160990"
        var vars = query.split("&");
        console.log(vars) //[ 'app=article', 'act=news_content', 'aid=160990' ]
        for (var i=0;i<vars.length;i++) {
                    var pair = vars[i].split("=");
                    console.log(pair)//[ 'app', 'article' ][ 'act', 'news_content' ][ 'aid', '160990' ] 
        if(pair[0] == variable){return pair[1];}
         }
         return(false);
}


class MemberOffline extends React.Component {

    constructor(){
        super();
        this.state = {
            data: []
        }
    }

    componentDidMount() {
        var th = this;


        const id = getQueryVariable('id');
        console.log("id", id );

        // webApi.get(`clinical/offlinemembers/${id}`)
        //     .then(res => {
        //         console.log("res", res);
        //     });

        webApi.get(`clinical/offlinemembers/${id}`)
            .then(function(event){
                console.log("event.data", event.data);
                th.setState({
                    data: event.data
                });
            });


    }

    render() {
        const contents = this.state.data.forEach(item => {
            //change the title and location key based on your API
            return <tr>
              <td>{item.member_name}</td> 
              <td>{item.member_ID}</td>
              <td>{item}</td>
              <td></td>
              <td></td>
            </tr>
        })
        return(
            <div class="container-fluid">
                <div>Case Trakker Dynamo Disconnect | TXAetna</div>
                <table class="table table-bordered">
                <tr>
                    <th>Member Name</th>
                    <th>Member ID</th>
                    <th>DOB</th>
                    <th>Current ILTCM Program Type</th>
                    <th>SAI Status</th>
                </tr>
                {contents}
                </table>
            </div>
        )
    }
}


export default MemberOffline;     

1 Answer 1

1

This should work:

  1. No need for var th = this;. You can use arrow functions and don't need to recover the context.

  2. Can't render objects in react, it'll throw an error. Hence the line <td>{item}</td> is not required.

  3. Map over forEach: because we don't need to cause side-effects to our data, map returns a new array altogether. State mutation is a big no in react.

    import React from 'react';
    import webApi from './api/webApi';
    import { withRouter, Route, Link, BrowserRouter as Router, Switch } from 'react-router-dom'
    import queryString from 'query-string';
    //import ActivateAccount from './ActivateAccount';
    
    
    function getQueryVariable(variable)
    {
            var query = window.location.search.substring(1);
            console.log(query)//"app=article&act=news_content&aid=160990"
            var vars = query.split("&");
            console.log(vars) //[ 'app=article', 'act=news_content', 'aid=160990' ]
            for (var i=0;i<vars.length;i++) {
                        var pair = vars[i].split("=");
                        console.log(pair)//[ 'app', 'article' ][ 'act', 'news_content' ][ 'aid', '160990' ] 
            if(pair[0] == variable){return pair[1];}
             }
             return(false);
    }
    
    
    class MemberOffline extends React.Component {
    
        constructor(){
            super();
            this.state = {
                data: []
            }
        }
    
        componentDidMount() {
    
            const id = getQueryVariable('id');
            console.log("id", id );
    
            // webApi.get(`clinical/offlinemembers/${id}`)
            //     .then(res => {
            //         console.log("res", res);
            //     });
    
            webApi.get(`clinical/offlinemembers/${id}`)
                .then((event) => {
                    console.log("event.data", event.data);
                    this.setState({
                        data: event.data
                    });
                });
    
    
        }
    
        render() {
            const contents = this.state.data.map(item => (
                //change the title and location key based on your API
                <tr>
                  <td>{item.member_name}</td> 
                  <td>{item.member_ID}</td>
                  <td></td>
                  <td></td>
                </tr>
            ))
            return(
                <div class="container-fluid">
                    <div>Case Trakker Dynamo Disconnect | TXAetna</div>
                    <table class="table table-bordered">
                    <tr>
                        <th>Member Name</th>
                        <th>Member ID</th>
                        <th>DOB</th>
                        <th>Current ILTCM Program Type</th>
                        <th>SAI Status</th>
                    </tr>
                    {contents}
                    </table>
                </div>
            )
        }
    }
    
    
    export default MemberOffline;
    
Sign up to request clarification or add additional context in comments.

8 Comments

1. i had to change item=> ( and closing to {.. } , but then i got error on this.setState({
Error for that is Objects are not valid as a React child (found: object with keys {member_name, member_ID, member_DOB, programType}). If you meant to render a collection of children, use an array instead.
Why did you have to change anything? Also, post the response you are getting from the server.
because i had to change... arrow function needs brackets not params
No you didn't have to do anything, the brackets represent a return statement, just use the code I posted and post the response from the server.
|

Your Answer

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