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

``Why is my setFeatureState function not updating the value in my Mapbox map

I've been attempting to change the stroke of a circle upon clicking it on mapbox. Despite following mapbox's documentation, the values don't seem to update. The console is also clear. t.map.addLayer({ id: id, type: 'circle&apo ...

Who is the father of Bootstrap Popover?

I'm currently facing an issue with getting a popover to be placed within a specific element. As of now, the popover is being inserted directly into the <body>, but I require it to be relative to other elements. I have been unable to locate a met ...

angular-recaptcha: Adjusting language based on the website's language update

My website offers three different languages that users can switch between. The language switch functionality is implemented on the client side using JavaScript (AngularJS). I have integrated reCAPTCHA 2 into my website and now I need to update the languag ...

Utilizing jQuery's each() function to create a seamless loop of background images in a

Struggling with looping the background image in a slick slider? Check out the code snippet below. var json = [ { "img_url": "https://via.placeholder.com/500x500?text=1" }, { "img_url": "https://via.placeholder.com/500x500?text=2" }, { "img_url": "ht ...

Loop through the v-for based on the input number that was selected

I'm looking to accomplish the following: if a user selects input X (a number between 1 and 10), I want to render a specific vue component X times. It seems to work if I use v-for n in 10, but not when I use variables. <template> <div> ...

Troubleshooting Type Conversion Error in ASP.NET MVC Controller

I have been working on an application that utilizes the following HTML and JavaScript. The user is required to input 5 props and then click on the 'Create' button. Subsequently, the JavaScript code compiles all of these props into a list before s ...

Ensuring the validity of float and non-empty values in JavaScript

Embarking on the journey of web development, I'm delving into basic applications. My current project involves creating a straightforward webpage to add two numbers and implementing preliminary validations - ensuring that the input fields are not left ...

Transferring String data between Java and JavaScript using Webview in both directions

I'm currently developing an application that allows two users to communicate via a webview. My goal is to transfer a String variable from JavaScript to Java in order to store it in my SQLite database, and also be able to do the reverse operation as we ...

Snap carousel for React Native

Currently tackling an issue with my react native expo app where I'm encountering the error: TypeError: Cannot read property 'array' of undefined, using the js engine Hermes. This problem seems to be connected to the Carousel package. I atte ...

What is the process for reversing the texture application direction on a CylinderGeometry object?

Is it possible to reverse the orientation of texture mapping on a CylinderGeometry object? var obj = new THREE.Mesh( new THREE.CylinderGeometry(20, 15, 1, 20), new THREE.MeshLambertMaterial({color: 0x000000}) //the material is later changed to the ...

How can you remove the add button in React Material Table?

Within the material table, there is a feature that allows for the conditional hiding/disabling of action buttons. Is there a way to do the same for the Add button located at the top of the table? See screenshot below ...

Stream JSON data to a file with Node.js streams

After reading this article, I decided to utilize the fs.createWriteStream method in my script to write JSON data to a file. My approach involves processing the data in chunks of around 50 items. To achieve this, I start by initializing the stream at the be ...

Navigation bar options across various web pages

In my Next JS project, I encountered an issue with the Navbar component. By default, the Navbar elements change color from white to black when scrolling below 950px. However, I needed to make an exception for another specific page ("/lodge/page.tsx"). On t ...

When using the jQuery datepicker with the minDate set to 0, any past dates entered in the text box will be automatically reset to the current date

How can I prevent users from selecting past dates in a jQuery datepicker, while keeping any existing past dates displayed as is? My current code looks like this: $("#t1").datepicker({ minDate:0 }); And the text box code is, <input type="t1" va ...

Show the user's name in an Express partial once they have logged in

I've been trying to find a solution for my issue without success. Here's the scenario: I have a homepage ('/'), a profile page ('/profile'), and a login/register page. I'm using passport with local, twitter, and google fo ...

Unable to set the cookie when using the fetch API

My node.js server is listening on port 3001. WITHIN THE REACT FILE On the login page component. fetch('http://localhost:3001/api/login',{ method:'POST', headers: { Accept: 'application/json', ...

Get the MAC address of a client using Node.js

I have a project in progress that aims to help my home automation system recognize the presence of individuals at home by using their MAC addresses as identifiers. In my attempt to collect the MAC address of a client on my network, I utilized Nodejs along ...

Is there a way to limit the rotation of an a-camera in aframe?

One scenario could be enabling rotation around the z-axis within a range of -70 to 70 degrees, or alternatively, preventing rotation around any arbitrary axis. Thank you! ...

Encountered an error: Trying to access 'location' property from undefined in express app

Encountered Issue : I am facing an error that is hindering me from fetching data from the HTML form. Every time I input values into the form and click the button to send the data to an API for saving it in the database, this error pops up: Cannot read pro ...

The ineffectiveness of setting width to 0

When I set @media screen and (max-width: 700px), aside {width: 0}, it doesn't disappear. Even after resizing the window, it remains as null space with width: 52px. What could be causing this issue and how can I resolve it? * { margin:0; padding ...