Developing a React Native app using Expo and Firebase? Learn how to prevent Firebase details from

I have encountered a problem with my code while working on the user edit profile page in my react native app. The issue I am facing is related to displaying the previously inputted firebase details from the collection in the text input fields when the user visits the page. My current code successfully achieves this functionality, but I am unable to make further modifications as any additional character entered disappears. I suspect that the issue lies within the getuserinfo function, but I'm unsure about an alternative implementation. If I remove the user info async function and integrate it into the handle press, then I can edit the details only after pressing save twice.

My goal is to find a way to display the details without requiring the user to press save beforehand.

Thank you!

export default function SignUp({ navigation }) {
    let currentUserUID = firebase.auth().currentUser.uid;
    const [fullname, setFullName] = useState('');
    const [bio, setBio] = useState('');
    const [studentCode, setCode] = useState('');
    const [location, setLocation] = useState('');
    const [dayofbirth, setDOB] = useState('');
    const [link, setLink] = useState('');
    const [image, setImage] = useState(null); // for profile pic
    
  

  
      async function getUserInfo(){
        const currentUser = firebase.auth().currentUser;
        let doc = await firebase
        .firestore()
        .collection('userProfile')
        .doc(currentUserUID)
        .get();
       
     
        
  
     
          let dataObj = doc.data();
          setFullName(dataObj.firstName);
          setCode(dataObj.code);
       
          setBio(dataObj.bio);
          setLocation(dataObj.location);
          setDOB(dataObj.dayofbirth);
          setLink(dataObj.link);
          setImage(dataObj.image);
          
          
        
      }
      getUserInfo(); // calls this function
  
    
      useEffect(() => { // works for just for IOS
        (async () => {
          if (Platform.OS !== 'web') {
            const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
            if (status !== 'granted') {
              alert('Sorry, we need camera roll permissions to make this work!');
            }
          }
        })();
      }, []);

      const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.All,
          allowsEditing: true,
          aspect: [4, 3],
          quality: 1,
        });
    
        console.log(result);
    
        if (!result.cancelled) {
          setImage(result.uri);
        }
      };

      const emptyState = () => {
        setFullName('');      
        setCode('');
        setBio('')
       
      };
  
  

    const handlePress = async () => {
      const doc = await firebase
      .firestore()
      .collection('userProfile')
      .doc(currentUserUID)
      .get();

    
     
        const currentUser = firebase.auth().currentUser;

      
          let dataObj = doc.data();
          setFullName(dataObj.firstName);
          setCode(dataObj.code);
          setLocation(dataObj.location);
          setBio(dataObj.bio);
          setDOB(dataObj.dayofbirth);
          setLink(dataObj.link);
          setImage(dataObj.image);
      
        if (!fullname && !bio && !studentCode) {
          setFullName(doc.data().firstName);
          setBio(doc.data().bio);
          setCode(doc.data().code);
          setImage(doc.data().image);
        } else if (!fullname && !bio) {
          setBio(doc.data().bio);
          setFullName(doc.data().firstName);
        } else if(!studentCode && !bio){
          setCode(doc.data().code);
          setBio(doc.data().bio);

        } else if (!studentCode) {
            setCode(doc.data().code)
        } else if(!fullname){
          setFullName(doc.data().firstName);
         
        } else if(!image){
          setImage(doc.data().image);
        }
        else if(!dayofbirth) {
          setDOB(doc.data().dayofbirth)
        }
        else if(!bio){
         
          setBio(doc.data().bio);

        } else {
          registration(
            bio,
            fullname,
            studentCode,
            location,
            dayofbirth,
            link,
            image
          );
          navigation.navigate('Loading');
          emptyState();
        
    
    
        }
        function useAsync(asyncFn, onSuccess) {
          useEffect(() => {
            let isMounted = true;
            asyncFn().then(data => {
              if (isMounted) onSuccess(data);
            });
            return () => { isMounted = false };
          }, [asyncFn, onSuccess]);
        }
        
      };

Answer №1

When getUserInfo(); is called at the top level of your component, it will be executed every time the component renders.

To prevent this, you should enclose it within a useEffect. If you only want it to run when the component mounts for the first time, you can specify zero dependencies like this:

useEffect(() => { getUserInfo(); },[])

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

What is the best way to split key and value into separate array objects using JavaScript?

Here's a snippet of code I am working with: let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'} var years = []; let i; for (i= obj;i<=obj;i++) { years.push({ edad_beneficiario : i }) } When I run this code, the output i ...

The alertify.alert function encounters issues when used within the response of a mithril m.request

I'm currently working on a project utilizing mithril.js and also integrating alertify.js. I am encountering an issue when trying to alert some data in the response. Strangely, it doesn't work as expected. However, if I use the same alert function ...

Angular confirmation page following successful HTTP POST request to Web API

First question here... I have been given the task of improving an Angular application, even though I am starting with zero experience in Angular. While I do have some background in JavaScript, I mostly work with Java (JSP's and yes, JavaScript). Despi ...

Converting JSON information into a JavaScript array of objects

I have a JSON file containing placeholder articles for testing purposes. I'm using jQuery to parse the data from the JSON file and create an array of objects with the retrieved information. Take a look at my JSON file: { "news": [ { ...

CORS headers not functioning as expected for Access-Control-Allow-Origin

Can someone help me figure out how to add Access-Control-Allow-Origin: 'http://localhost:8080' in Node.js and Express.js? I keep getting this CORS error: Access to XMLHttpRequest at http://localhost:3000 from origin 'http://localhost:8080&ap ...

Adding a class to an img tag with TinyMCE

Currently, I am utilizing the TinyMCE editor as a standalone editor in my content management system (CMS). Within the CMS, there is an automatic setting that adds a curved border to any image tags within the cms div ID. In certain cases, I require the op ...

What are some ways to design scrollbars with a Google Wave-like style?

Is there a way to design scrollbars similar to the ones found in Google Wave? They seem to save space and have an appealing look. I am interested in implementing these customized scrollbars on a div element, just like how Google Wave utilizes them. (im ...

JavaScript's Selenium WebDriver - Explicit Waiting

Currently, I am utilizing selenium-webdriverjs. My objective is to pause until a specific element is displayed. To accomplish this, I have implemented an explicit wait that operates effectively: var shown = false; driver.wait(function(){ driver.findEl ...

Deactivating a button if the input fields are blank using ReactJS

Hi there, I'm new to reactJS and recently encountered an issue with my code. Everything seems to be working fine except for the NEXT button not being disabled when text fields are empty. My expectation is that the NEXT button should only be enabled af ...

Using a variable as an argument for a DOM function in JavaScript

I found this code snippet on a website and made some changes to it. However, the modified code below is not functioning as expected. My goal was to hide the div with the id "demo1", but for some reason, it's not working. What could be causing this is ...

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

What methods are available to adjust the header color on various pages?

I have a solution that works for one location, but I need to add red color to multiple locations. How can I achieve this? import { useRouter } from "next/router"; function Header() { const router = useRouter(); return ( <> & ...

Changing the colors of multiple buttons in a React Redux form: a step-by-step guide

When using Redux Form Wizard on the second page, I have two buttons that ask for the user's gender - Male or Female. The goal is to make it so that when a user clicks on either button, only that specific button will turn orange from black text. You ...

What is preventing the bundling of my CSS into the application?

I'm facing an issue while setting up a new project using vue.js, scss, and webpack (with express.js on the server side and TypeScript). I copied over the configurations from a previous project where everything was working fine. According to my underst ...

Transforming the hide/show functionality from JQuery to Vue

I created some hide/show panels using jQuery that I want to implement in Vue. However, when I try to integrate the jQuery functions into Vue, the functionality doesn't seem to work properly. The panels are not hiding/showing as expected. Does anyone ...

After the initial rendering, JQuery can dynamically search through the DOM elements and seamlessly replace keys with their respective values

I am in the process of implementing my personal localization method on my web application that is currently under development. With the use of JQuery 2.2.0 and no other frameworks or third-party tools, I need to embed certain expressions directly into my H ...

The text box remains disabled even after clearing a correlated text box with Selenium WebDriver

My webpage has two text boxes: Name input box: <input type="text" onblur="matchUserName(true)" onkeyup="clearOther('txtUserName','txtUserID')" onkeydown="Search_OnKeyDown(event,this)" style="width: 250px; background-color: rgb(255, ...

What is the best way to retrieve a jobID from Kue?

I am currently working with Express and I'm facing a challenge in creating a job whenever someone posts to my route. My goal is to have the response include the job.id, but the job id is only generated within the callback of my queue.createFunction. I ...

What are the reasons for a jQuery function to run in a selective manner?

There seems to be some inconsistency in the behavior of this incomplete script that I'm trying to debug. The issue arises when I click off an item, as sometimes the $(editObj).removeAttr('style'); line of code executes and other times it doe ...

Sharing information in React applications

I'm a beginner when it comes to using javascript and React, so I have a question regarding posting data from within a component. In my scenario, I am utilizing the fetch API for making POST requests. Below is the code snippet I have created: export f ...