how to run firebase update once?

Viewed 41

I have a button and when we press it, Firebase updates some value in Firebase. How can I control users? When we press it, Firebase updates some value in Firebase. How can I control users' presses? And allow the user to press this button only once?

My idea is that when opening some page in useEffect, I check if this user pressed a button earlier (I store all users' IDs to check if a user pressed a button) and if there is no user ID, then I allow the user to press the button, but if there is a user ID, then I disable the button and the user can't press it again. But here is some problems. When user open page while firebase checks if there is user button is available for pressing. This is problem and I dont' want to allow do that.

And also if previosly user didn't press the button and now wants to do that then I need to imidiatelly disable it to prevent pressing it more than once.

  1. How To disable button while data is fetched from firebase (on page loading)
  2. How To disable button after 'click'
1 Answers

Here's a test component which accomplishes what you are asking:

import React, {useEffect, useState} from 'react';
import { Button } from 'react-native-paper';

const Test = props => {
    const [isButtonDisabled, setIsButtonDisabled] = useState(false);

    useEffect(() => {
        const fetchMyAPI = async () => {
            setIsButtonDisabled(true) // Disable button

            let response = await fetch('api/data')
            response = await response.json()
            // Do whatever you want with response

            setIsButtonDisabled(false) // Enable button after fetching
        }
    
        fetchMyAPI()
    }, [])

    const onPressHandler = () => {
        setIsButtonDisabled(true)
        // Button functionality can go here
    }

    return (
        <Button onPress={onPressHandler} disabled={isButtonDisabled}></Button>
    );
};

export default Test;

This is for react native so just replace the react native Button with whatever button you want to use.

Edit: If you are having a problem with the button disabled state when reloading this component it is likely due to the component re-rendering. You will have to lift the state up to the parent and pass the state back down to the children. This will avoid the state being reset when the button gets re-rendered. See the react docs https://reactjs.org/docs/lifting-state-up.html

Related