Leveraging "setState" in React Native with Promises

I am facing a challenge in updating the state of a React Component with data obtained from an API call. I encountered an issue where using the setState function within the promise resulted in an error "Type Error: _this2.setState is not a function" in React Native. The code snippet below demonstrates my approach:

let foodList = [];
        Firebase.auth().onAuthStateChanged(function(user) {
            if (user) {
                Firebase
                    .firestore()
                    .collection(`/userProfiles/${user.uid}/foodList`)
                    .get()
                    .then(foodListSnapshot => {
                        foodListSnapshot.forEach(snap => {
                            foodList.push({
                                foodName: snap.data().name,
                                mealConsumed: snap.data().meal,
                                estimatedCalories: snap.data().calories,
                                dateConsumed: snap.data().date
                            });
                        });
                    }).then((foodList) => {
                        this.setState({data: foodList});
                    }).catch(error => console.log(error));
            } else {
                Alert.alert('User not signed in');
            }
        });

My objective is to trigger a re-render of the component once the 'data' field in its state has been updated.

Despite attempting to use bind.this, as a beginner in React Native, I have struggled to resolve this issue on my own. Any assistance or guidance would be greatly appreciated! :)

Answer №1

It is important to update function(user) to (user) => {}, as the function() does not properly bind the outer scope(state). Here is how the updated code should look:

let foodList = [];
        Firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                Firebase
                    .firestore()
                    .collection(`/userProfiles/${user.uid}/foodList`)
                    .get()
                    .then(foodListSnapshot => {
                        foodListSnapshot.forEach(snap => {
                            foodList.push({
                                foodName: snap.data().name,
                                mealConsumed: snap.data().meal,
                                estimatedCalories: snap.data().calories,
                                dateConsumed: snap.data().date
                            });
                        });

                    }).then((foodList) => {
                        this.setState({data: foodList});
                    }).catch(error => console.log(error));
            } else {
                Alert.alert('User not signed in');
            }
        });

This adjustment will ensure that state is accessible within the function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Saving information in node.js

My latest project involves creating an address book app using HTML, CSS, and JavaScript. The company provided me with a zip file containing the necessary resources to implement the app using node.js. However, my knowledge of node.js is limited and I have ...

Adjusting the color of a box in Threejs through dat.gui.min.js controls

I want to enhance the user experience by allowing them to choose a color from the HEX menu and update the color of the box in the scene using UI controls. Below is the JavaScript code I have implemented for this purpose: // author: Arielle Mueller // date ...

Why Does React Material-UI Switch Styling Keep Changing Sporadically?

Currently, I am trying to integrate a switch component from MUI into my code. Strangely enough, upon the initial page load, the switch appears exactly as it should - identical to the one displayed on the MUI site. However, upon reloading the page, it under ...

The call stack in mongodb has surpassed its maximum size limit

I am currently executing a method. Method execution var message = "Hello" function1("78945612387", message, null, "Portalsms") Node JS Code function function1(mobileno,body,logExtraInfo,messageType){ request(uri, function (error, resp ...

Decipher intricate JSON with JavaScript

After retrieving a JSON object from Mongo DB, I have this data structure. **JSON** { "_id" : ObjectId("5265347d144bed4968a9629c"), "name" : "ttt", "features" : { "t" : { "visual_feature" : "t", "type_feature" : ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

Implementation of internationalization into a JSON-formatted data file

I recently integrated i18n into my application and I'm facing a challenge with implementing the useTranslation(); function in my navbar data file. This file serves as the database for the page titles and tabs, and I'm unsure about how to proceed. ...

AngularJS IP Address masking

Looking for an IP address mask plugin that works with AngularJS. I attempted to use the "Jquery Input IP Address Control" plugin, but it wasn't functioning properly. The problem I encountered was that the "ngModel" attribute wasn't capturing the ...

Using NodeJS to retrieve the mean price from the OPSkins pricelist

Is there a way to calculate the average price of every skin listed in this document? I'm wondering how one would go about using the dates and prices in order to determine the 60-day average price. My approach would involve extracting the data from t ...

The jQuery slider does not have the functionality to be dragged

My Ruby on Rails app is utilizing a jQuery slider, but I am encountering an issue where I am unable to drag the slider button. However, it does move successfully if I click anywhere inside the slider. Here is the code snippet: <div id="slider">< ...

What is the process for using Discriminators, the Mongo DB API, and Mongoose to insert data into Cosmos DB?

Issue Overview I am currently facing a challenge in writing documents to my Cosmos DB using the Mongo DB API and Mongoose for Object Modeling. To optimize costs, I aim to store all documents in a single collection by utilizing Discriminators. The project ...

Issue with horizontal scrolling in ng-scrollbars occurs when scrolling from right to left

We are currently developing a single page application that supports two languages, one being right to left and the other left to right. For scrolling functionality, we have implemented ng-scrollbars, an Angularjs wrapper for the malihu-custom-scrollbar-pl ...

Tips for redirecting a page in React by forcing a route

Attempting to implement the guidance from this Stack Overflow solution on how to "go back home" after closing a Modal... import React, { Suspense, useState } from 'react'; import { BrowserRouter, Route, Switch, useHistory } from "react-route ...

What is the reason for the lack of an applied CSS selector?

.colored p{ color: red; } article > .colored{ color:powderblue; } .blue{ color: white; } <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initi ...

transfer scope variable to scope function

I notice this pattern frequently view: <input ng-model="vm.model"> <button ng-click="vm.method(vm.model)"></button> controller: function Controller() { var vm = this; this.method = function(parameter) { // perform acti ...

Angular code is failing to send a signal to the server following a $http.post request

I've been using angular for about a week now and I've been struggling to solve this issue. I have a service that wraps around $http because multiple controllers make calls to the same URL. On one particular page, there is a lot of server-side bus ...

Failure to execute the success function

My current issue involves making an AJAX call to retrieve a record from the database. Despite console logs showing that the record is successfully returned, the success function fails to execute. function ajaxForParent() { var search = document.getEle ...

Enhance your browsing experience by inputting valuable information into the

I am looking to enhance a text box by adding values. The text box already has a default value of 10, and I want to create a button that will add new text boxes with a limit of 4. My goal is to continuously add values from text box 1 to text box 4. For exa ...

refreshing datatables with updated data from a different endpoint

Need help reloading datatables with the new ajax feature? I suspect it might be a scope issue. function refreshTable(tableName, src) { var table = $('#'+tableName).DataTable({ 'bProcessing': true, 'bServerSide ...

Execute the knockout function using jQuery

There's a scenario where I am trying to trigger a knockout method using jQuery. The Knockout viewModel has already been bound, but I'm unsure of how to call it using jQuery. Below is the snippet of my code: $(document).ready() { form_submit( ...