dfro
dfro

Reputation: 27

React dev tools show empty state, console shows data

I'm having a strange issue with state in my React app. I set initial state as an empty array and in the componentDidMount() method I retrieve some data from Firebase. I put the JSON objects into a new array and call setState(), passing it the new array.

The problem is that it doesn't seem to be updating state. From what I can tell:

  1. Render() is being called after setState
  2. My callback on setState() is being fired
  3. When I console.log the array that I set the state to, it looks fine
  4. The strangest thing, when I inspect state in the Chrome React Devtools, it shows empty but for some reason I can print the array to the console using $r.state.nameOfMyObjectenter image description here
  5. If I change some other piece of state directly from the dev tools, the app immediately renders and finally displays the piece of data I've been struggling with all along.

I thought maybe there was some issue with updating the array; maybe the diffing algorithm didn't go deep enough to see that the data inside the array changed. To test this, I tried to set the initial state of the object in question to null, but then set off errors throughout the app that it was trying to call various array methods on null.

I've tried walking through the app, console logging each step, but I can't find the issue.

Snippet of initial state:

  state = {
    fullSchedule: [],
    currentSet: [],
    aCoupleOfOtherObjects,
}

componentDidMount():

  componentDidMount() {
    const activities = [];
    const projectReference = firestoreDB.collection("project").doc("revision001").collection("activities");
    projectReference.get().then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
        activities.push(doc.data());
      });
    });
    console.log(activities);
    this.setState({fullSchedule: activities});
    this.setState({currentSet: activities}, () => {
      console.log("State updated from DB");
    });
    console.log("called setstate");
  }

I can't tell why the setState() method doesn't seem to be setting the state, any ideas? Thanks!

Upvotes: 0

Views: 726

Answers (1)

Hamza El Aoutar
Hamza El Aoutar

Reputation: 5657

projectReference.get() is asynchronous, and you are trying to set the state right after you call it, which won't work.

try setting the state inside then callback:

projectReference.get().then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
    activities.push(doc.data());
  });

  this.setState({fullSchedule: activities, currentSet: activities});
});

This should give you a better idea of what's going on.

Upvotes: 1

Related Questions