Home > Software engineering >  Call a function once onPress then display other function
Call a function once onPress then display other function

Time:01-15

I'm doing a react-native school project and i'm willing to know how to call a function on first press then display another function on other clicks :

<TouchableOpacity style={styles.btnMiddle} onPress={() => buyFishes(1)}>
    <View style={styles.fish}>
        <Text style={styles.shptxt}>50</Text>
        <Image style={styles.coin2}source={require("../../assets/img/coin.png")} />
    </View>
</TouchableOpacity>

here is my button, in my project this button is displayed on the Shop Screen and I need it to cost 50 on the first press (to unlock it), then I want it to stop costing 50 and just call another function.

here is my function to buy an item

const buyFishes = (id) => {
    fishes.map(fishes => {
        if(fishes.id === id)
        {
            if(Gold >= fishes.cost)
            {
                setGold(Gold - fishes.cost);
            }

        }
            if (Gold < fishes.cost)
            {
            onPress: () => Alert.alert("Not enough Gold Kiddo !");
            }

        }
    );
};

Any Idea ? Thanks

CodePudding user response:

Just add a state to your component and use it to call the functions you want accordingly.

const [clicked,setClicked] = useState(false);
<TouchableOpacity style={styles.btnMiddle} onPress={onPressHandler}>
    <View style={styles.fish}>
        <Text style={styles.shptxt}>50</Text>
        <Image style={styles.coin2}source={require("../../assets/img/coin.png")} />
    </View>
</TouchableOpacity>
const onPressHandler = (id) => {
    setClicked(true);
    if(clicked)
    {
      // call second function
    }
    else 
    {
      // call first function
    }
};
  • Related