3

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It worked well, thanks a lot for the solution and the explanations !
Glad to hear it. It can be handy to always have this in your render function when developing: console.log('render', this.props, this.state); so you can watch all updates and also see if you need to optimize to reduce re-renders with a shouldComponentUpdate function.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.