React this.state undefined array

Viewed 7622

I have an issue with React. I have an array that I pass to this.state. But I'm facing an issue, I can't access to the sub-elements in the array. In my case, I can't access to this.state.folders[0].

Here is my code :

class DriveContent extends Component {
    constructor () {
        super();
        let list_files = [];
        let list_folders = [];
        axios.get('/api/getFilesAndFolders').then((response) => {
            for (var i = 0; i < response.data.length; i++) {
              if (response.data[i]["isFile"] ==true){
                  list_files.push(response.data[i]);
              }
              else {
                  list_folders.push(response.data[i]);
              }
            }
        }).catch((error) => {
             console.error(error);
        });

       this.state = {files: list_files, folders: list_folders};
       console.log(this.state.folders);
       console.log(this.state.folders[0]);
    }

Here is what return the the 2 console.log :

// console.log(this.state.folders);
        []
    0: "Commun"
    1: "Privé"
    2: "Public"
    length: 3

//console.log(this.state.folders[0]);
    undefined

Thanks in advance !

1 Answers

You are setting state too soon. In your callback function you need to setState after assigning to list_files and list_folders since the callback is executed after the constructor has finished. Try this:

for (var i = 0; i < response.data.length; i++) {
     if (response.data[i]["isFile"] ==true){
       list_files.push(response.data[i]);
     }
     else {
       list_folders.push(response.data[i]);
     }
}
// setState here:
this.setState = {files: list_files, folders: list_folders};

Then move your console.logs to your render function to see the state being updated. Once on initial construction and once again after setState.

Related