Home > Software engineering >  Function Runs on Each Render ReactNative
Function Runs on Each Render ReactNative

Time:07-11

I have got a function that should remove an item from a cart on button click. However when I navigate to that a specific cart page the function runs immediately. note: Right now I'm only logging out the ids of the items in the cart. So when I get to the cart page the ids are logged out immediately. Any help will be appreciated .The ids Should be logged out only when I click the x icon

const removeItem=useMemo(()=>(ids)=>{
  [ids].map((id, i) => {
    console.log(id)
  })
 },[removeItem])

Am calling the removeItem on an Onpress and passing the id as a parameter

 <ScrollView>
    {cart && cart.map((item, i) => {
      return (
        <View style={styles.box} key={i}>
          <View style={styles.top} >
            <Text style={styles.itemname}>{item.product.itemname}</Text>
            <View style={styles.right}>
              <Text style={styles.qty}> {item.product.price}</Text>
              <Text style={styles.qty}> x {item.qty}</Text>
              <View>
                <Pressable onPress={removeItem(item.product.id)} >
                  <FontAwesomeIcon icon={faXmark} />
                </Pressable>
              </View>
            </View>

          </View>
          <Text style={styles.subTotal}>subTotal:  Ksh. {item.totalPrice}</Text>
        </View>
      )
    })}
    </ScrollView>

CodePudding user response:

In <Pressable onPress={removeItem(item.product.id)} > you are not assigning the function but are calling it. Changing it to <Pressable onPress={() => removeItem(item.product.id)} > will solve this.

You probably made this mistake because you are used to assigning functions to events like onClick by simply typing onClick={myFunction} which is correct but as soon as parameters come into to play you need change the syntax like mentioned above.

  • Related