0

I'm using a state library called unstated and when I run the following code:

import { Container } from 'unstated';
import Fire from '../Core/Fire';

class Store extends Container {
  state = {
    users: [],
  };

  getAllUsers() {
    const db = Fire.firestore();
    const reference = db.collection('users');
    reference
      .get()
      .then(snapshot => {
        const docs = [];
        snapshot.forEach(doc => {
          docs.push(doc);
        });
        this.setState({
          users: docs.map(doc => {
            return {
              id: doc.id,
              model: doc.data(),
            };
          }),
        });
      })
      .catch(error => {
        console.error(error);
      });
  }
}

export default Store;

I get this error:

TypeError: Cannot read property 'setState' of undefined at Store.js:19

I'm definitely getting results back as docs does contain objects at the time I want to set the state. I'm also doing things exactly the same way they are in their documentation / example.

Why isn't the reference this seen? Is it because it's in a promise? Doh!

  • 1
    Try `getAllUsers = () => { ... }` instead. –  Jun 20 '18 at 11:19
  • @ChrisG it works! But why? What's the difference? –  Jun 20 '18 at 11:20
  • See: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback –  Jun 20 '18 at 11:21
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – PatrickSteele Jun 20 '18 at 13:13

1 Answers1

1

You should either bind the function or use arrow function.

1.)

constructor(){
this.getAllUsers=this.getAllUsers.bind(this) 
}

2)

getAllUsers = () =>{ ... }
Rohith Murali
  • 5,551
  • 2
  • 25
  • 26