Oula R.
Oula R.

Reputation: 35

React native calling a function from a conditional statement

     <Pressable onPress={()=> {
            if(newID) {
              EditPress(newID)
            } else {
              AddPress
            }
          }}
            style={styles.logBox} >
           <Text style={{ textAlign:"center",bottom:12,fontWeight:"bold"}} > Save </Text>
    </Pressable>

I've been trying to make a component in react native which can either edit a movie or add a new movie to my List. I want to use an onPress function to call either of functions I created for fetching data. How can I use both functions with an if/else statement inside onPress. Especially when one of the functions will get parameters -which is the id for the movie I want to edit- and another function will not get any parameters.

Upvotes: -1

Views: 87

Answers (1)

Mister_CK
Mister_CK

Reputation: 1063

  <Pressable onPress={()=> {
    if(newID) {
      EditPress(newID)
      return // using early returns, so that you don't need else is a good practice.
    } 
    AddPress()
  }}
  style={styles.logBox} >
    <Text style={{ textAlign:"center",bottom:12,fontWeight:"bold"}} > Save </Text>
  </Pressable>

You need to call Addpress by adding (). And I don't know where you are getting the newID from, but you might have to pass that as a parameter to onPress (add it inside the () before the arrow) You can also extract the function from the jsx and define it earlier:

pressHandler = ()=> {
  if(newID) {
    EditPress(newID)
    return // using early returns, so that you don't need else is a good practice.
  } 
  AddPress()

You can then call it in the onPress, which I find easier to read.

  <Pressable onPress={pressHandler} style={styles.logBox} >
    <Text style={{ textAlign:"center",bottom:12,fontWeight:"bold"}} > 
      Save 
    </Text>
  </Pressable>

If you need to pass args to PressHandler:

<Pressable onPress={() => pressHandler(args)} style={styles.logBox} >

Upvotes: 0

Related Questions