Search code examples
reactjswebreact-state

React return state


import React from "react";
import { renderToString } from 'react-dom/server'


export default class Tokens extends React.Component {
  state = {
    loading: true,
    number: null
  };


  async outDataTockens(val){
    val.forEach((ele,ind) =>{
      console.log(ele);
    })
  }

  async componentDidMount() {
    let tokensvar = '<tr> <td>1</td> <td>2</td> </tr>';
    const url = "https://api.multiversx.com/accounts/erd1n0kgesdn7hc63amdfygqfdj9enfa07n2hwup9y8732fg35qcug8q0w0x8s/tokens";
    const response = await fetch(url);
    const data = await response.json();
    data.forEach((ele,ind) =>{
      tokensvar += '<tr> <td>{ele.name}</td> <td>{ele.name}</td> </tr>';
                  
      //<tr> <td>{ele.name}</td> <td>{ele.name}</td> </tr>
      //tokensvar + " " + ele.name;
      //console.log(JSON.stringify(tokensvar));
      this.setState({ number: tokensvar, loading: false });
      //console.log(this.state.number);
    })
    //console.log(this.state);
  }

  

  render() {
    if (this.state.loading) {
      return <div>loading...</div>;
    }

    if (!this.state.number) {
      return <div>didn't get number</div>;
    }
    


    return (
      <div>
        <table className="Token-section-output"> {this.state.number} </table>
      </div>
      
    );
  }
}

why {this.state.number} return : "xxxx" And how to do for this return : xxxx

???

enter image description here

I dont know what i must do I tried a lot of things but I don't know what to do I'm lost, but I still think it's a simple error and easy to solve aresolved for an experimenter, in any case thank you in advance for your help.


Solution

  • Pls update the data into component's state as an array and then render using map fun.

    here is an example

    • update API response
     const data = await response.json();
     this.setState({ rows: data });
    
    • render table's row
     render(){
       <table className="Token-section-output">
        <p>table row</p>
        {rows.map((row) => (
          <tr>
            <td>{row?.name}</td>
          </tr>
         ))}
       </table>
     }
    

    if it is possible, we should use reactHook to manage the state of components and there are many benefits. smaller components and easy to control the state and so on.