0

I am new to React and javascript as whole. I want to receive data from the server and render it on the front-end. the data I get is in array form, so I loop through the data to save it to an array and then loop back through the array to render the elements in un-ordered list. when I console.log() the data, it shows what I receive but when I console.log() the length of array it shows 0 and doesn't add what I receive. if any clue please, please respond. any help would be really appreciated.thanks

constructor(){
    super();
    this.notes = [];
}

componentDidMount() {
    axios.get('http://localhost:4000/getnotes')

    .then(response =>{
        response.data.forEach((note)=>{
                console.log(note.title), 
                this.notes.push(note) // something isn't quite right here
            }
        )
    });
    console.log(this.notes.length);
}
render(){
    return(
        <div>
            <ul><li>default li</li>
                {
                    this.notes.map((note)=>{
                        return(
                            <li>
                                {note.title}
                            </li>
                        );
                    })
                }
            </ul>
        </div>
    );
}
  • may the comma after console.log(note.title), should be ; -> console.log(note.title); – toto Feb 21 '18 at 21:28
  • are you sure that this.notes exist inside foreach. this refer to response data? may the var should declare external and use notes.push(note) without this. – toto Feb 21 '18 at 21:30

2 Answers2

0

Data received from server is async in nature, so you won't be able to see this.notes.length right after sending off the ajax request

I'd suggest you store results from the server in the state and let React update the DOM when state changes, updated code below:

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

componentDidMount() {
    axios.get('http://localhost:4000/getnotes')

    .then(response =>{
        this.setState({
            notes: response.data
        });
        //response.data.forEach((note)=>{
        //      console.log(note.title), 
        //      this.notes.push(note) // something isn't quite right here

        //}
        //)
    });
    console.log(this.notes.length);
}
render(){
    return(
        <div>
            <ul><li>default li</li>
                {
                    this.state.notes.map((note)=>{
                        return(
                            <li>
                                {note.title}
                            </li>
                        );
                    })
                }
            </ul>
        </div>
    );
}
Varinder
  • 2,634
  • 1
  • 17
  • 20
0

I suggest to put notes in the state of the component, and update it using setState.

Yossi
  • 5,577
  • 7
  • 41
  • 76