skip to Main Content


import React, {Component} from "react"
import './index.css';

export default class ListArticle extends Component {
    constructor(props) {
        super(props);
        this.state = {
            arrayJson: [""],
        }
    }
    get() {
        fetch("http://localhost:8080/getHeaders", {
            method: "GET"
        })
            .then(data=>data.json())
            .then((data)=>{
                    this.setState({arrayJson:data.headerArray})
                }
            )
    }

    componentDidMount() {
        this.get();
        for(let i=0;i<4;i++) {
            let n="";
            let header = this.state.arrayJson[i];
            let t=true;
            for (let j = 0; j < 120; j++) {

                n += header[j];
                if (n === header) {
                    t = false;
                    break;
                }
            }
            if (t) {
                n += "...";
                console.log(n);
            } else {
                console.log(n);
            }
        }
    }


    render() {

        return (

            <div id={"container"}>

            </div>
        );
    }
}

this is my listArticle class

i need to get list of String values and after this I check every element and if the element length is more than 120 symbols i stop to read string element and add "..." to element and than i put it on console.log

but problem is that console of brower shows me this

enter image description here

and also it gives me
enter image description here
And as far as I can tell, the fact is that the first element is undefined or or the list doesn’t have time to initialize, I haven’t figured it out yet

if you just try to output the list after initialization:

import React, {Component} from "react"
import './index.css';

export default class ListArticle extends Component {
    constructor(props) {
        super(props);
        this.state = {
            arrayJson: [""],
        }
    }
    get() {
        fetch("http://localhost:8080/getHeaders", {
            method: "GET"
        })
            .then(data=>data.json())
            .then((data)=>{
                    this.setState({arrayJson:data.headerArray})
                }
            )
    }

    componentDidMount() {
        this.get();

    }


    render() {

        return (

            <div id={"container"}>
                {console.log(this.state.arrayJson)}
            </div>
        );
    }
}

console gives this:enter image description here
what wrong?

2

Answers


  1. So componentDidMount is only called once when the component is mounted, and likely before your fetch has resolved to update the state. Because of this you are only running your logic once with the state being arrayJson: [""]. You will be getting your undefined’s from the concatenated value of header[j] where i is equal to 0 making header the value of “”. This is because the index of header[0…120] don’t exist in the string “”.

    After this you will get an exception as i goes higher to 1 as arrayJson: [""] only has one element (arrayJson[0]) making header equal undefined. header[0] will give you an exception as the header is undefined.

    The reason why you can see it in the render function is because render will re-run each time the state or parent has changed…

    I would suggest having a look into class lifecycle functions for react here, especially componentDidUpdate. Or better yet move the logic into the then section of the fetch before placing it into state. You can also eliminate the nested loop using String.slice and String.length 🙂

    Login or Signup to reply.
  2. You’re not waiting for the get() to finish, so arrayJson will be [""]; trying to access it past the zeroth item leads to you looking at a whole bunch of undefined.

    Here’s a cleaned up version:

    • arrayJson starts out as null, so we know it’s not loaded yet
    • get() is now an async function so you don’t have a pyramid of .then()s
    • the data processing happens in render(), so we can, well, eventually render it out
    • in render(), if the array is null, we do nothing
    • truncatedHeaders is computed in a more functional way (I’m making some assumptions about your data format here).
    import React, { Component } from "react";
    import "./index.css";
    
    export default class ListArticle extends Component {
      constructor(props) {
        super(props);
        this.state = {arrayJson: null};
      }
    
      async get() {
        const resp = await fetch("http://localhost:8080/getHeaders");
        const data = await resp.json();
        this.setState({arrayJson: data.headerArray});
      }
    
      componentDidMount() {
        void this.get();
      }
    
      render() {
        if(!this.state.arrayJson) return null; // not loaded yet
        let truncatedHeaders = this.state.arrayJson.slice(0, 4).map(header => {
          if (header.length > 120) {
            return header.substring(0, 120) + "...";
          }
          return header;
        });
        return <div id="container">{JSON.stringify(truncatedHeaders)}</div>;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search