How to make a button visible after function runs. React Native

Viewed 143

I'm working a app that will check and API to see if there are active users, if there are active users I want to show a button a tt he bottom of the page I'm calling the function 2 seconds after the page load, because if I don't do this I get an error

"Too mnany re-renders. React limist the number of.."

and the only for me to fix this was to do the timeout.

After two second the function is called and setActive to true, but my button doesn't appears.

Yes I'm new to react native :/

export default function Index({navigation}) {

    const [active, setActive] = useState(true);

    const checkForActive = () => {
        console.log("Actives");
        setActive(true);
    }

    setTimeout(() => { 
        checkForActive();
    }, 2000);

    return ( 
        <View style={styles.MainContainer}> 
                {!active && (
                    <TouchableOpacity activeOpacity={.45} style={styles.BNutton} > 
                        <Text style={styles.Text}>   Active</Text>
                    </TouchableOpacity>
                    )
                } 
        </View>
    ); 
}
1 Answers

You should use an effect for this:

As checkForActive calls an API, it's asynchronous, so I'm assuming it will eventually return a Promise

useEffect(() => {
  checkForActive.then(data => {
    // Do things with data
    setActive(true);
  });
}, []);

The effect will be triggered once on first rendering of the component, then the empty dependencies array as second parameter means that nothing will trigger the effect again during the component life time.

Related