Eric
Eric

Reputation: 23

How to setState after getting data from Firestore

I am currently able to get user data from the Firestore however I'm having trouble saving the users document data. I'm getting an error below in my console

  TypeError: this.setState is not a function
    at Object.next (RepRequest.js:32)
    at index.cjs.js:1344
    at index.cjs.js:1464

I attempted to follow another user's question from Can't setState Firestore data, however still no success.

I do have a two api request right after getting the data and I am able to setState then. I tried incorporating the Firestore request in the promise.all but was unable to successfully, which is why I have it separated. Maybe I'm headed down the wrong path, any guidance is appreciated.

import React, { useEffect, useState } from "react";
import app from "./config/base.js";
import axios from "axios";

export default class RepRequest extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userInfo: [],
      fedSens: [],
      fedReps: []
    };
  }

  componentDidMount() {
    const items = [];
    app.auth().onAuthStateChanged(function(user) {
      if (user) {
        console.log("User is signed in");
        let db = app
          .firestore()
          .collection("user")
          .doc(user.uid);
        db.get().then(doc => {
          if (doc.exists) {
            console.log("Document data:", doc.data());
            items.push(doc.data());
          } else {
            console.log("No doc exists");
          }
        });
      }
      this.setState({ userInfo: items });
    });

    Promise.all([
      axios.get(
        `https://api.propublica.org/congress/v1/116/senate/members.json`,
        {
          headers: { "X-API-Key": "9wGKmWl3kNiiSqesJf74uGl0PtStbcP2mEzSvjxv" }
        }
      ),
      axios.get(
        `https://api.propublica.org/congress/v1/116/house/members.json`,
        {
          headers: { "X-API-Key": "9wGKmWl3kNiiSqesJf74uGl0PtStbcP2mEzSvjxv" }
        }
      )
    ]).then(([rest1, rest2]) => {
      this.setState({
        fedSens: rest1,
        fedReps: rest2
      });
    });
  }

  render() {
    if (this.state.fedReps.length <= 0)
      return (
        <div>
          <span>Loading...</span>
        </div>
      );
    else {
      console.log(this.state.fedReps);
      return <div>test</div>;
    }
  }
}

Upvotes: 2

Views: 426

Answers (1)

samthecodingman
samthecodingman

Reputation: 26171

Your problem arises from mixing lambda function declarations ((...) => { ... }) and traditional function declarations (function (...) { }).

A lambda function will inherit this from where it was defined but a traditional function's this will be isolated from the context of where it was defined. This is why it is common to see var self = this; in legacy-compatible code because this usually didn't match what you wanted it to.

Here is an example snippet demonstrating this behaviour:

function doSomething() {
  var anon = function () {
    console.log(this); // 'this' is independent of doSomething()
  }
  
  var lambda = () => {
    console.log(this); // inherits doSomething's 'this'
  }

  lambda(); // logs the string "hello"
  anon(); // logs the 'window' object
}

doSomething.call('hello')

Solution

So you have two approaches available. Use whichever you are comfortable with.

Option 1: Use a lambda expression

app.auth().onAuthStateChanged(function(user) {

to

app.auth().onAuthStateChanged((user) => {

Option 2: Assign a "self" variable

const items = [];
app.auth().onAuthStateChanged(function(user) {
  // ...
  this.setState({ userInfo: items });
}

to

const items = [];
const component = this; // using "component" makes more sense than "self" in this context
app.auth().onAuthStateChanged(function(user) {
  // ...
  component.setState({ userInfo: items });
}

Upvotes: 2

Related Questions