skip to Main Content

I am trying to call a function when a button is pressed but nothing happens.
I added a console.warn() in the function but it is never printed.
Have changed similar stack overflow answers but I still can’t figure it out.

Could someone help me out ?

Where the call should happen

</View>
     <View style={styles.infoContainer}>
  <BlueButton
    onPress={()=>  this.addToBlue  }
  />

The functions

const saveFavoriteRecipe = async () => {
  try {
    const value = await AsyncStorage.getItem("favoriteBlue");
    const existingBlue = value ? JSON.parse(value) : [];
    const updatedBlue = [...existingBlue, item];
    await AsyncStorage.setItem(
      "favoriteBlue",
      JSON.stringify(updatedBlue)
    );
    console.log("Blue added to Bluefavourites:", item);
  } catch (error) {
    console.log("Error saving Bluefavorite :", error);
  }
  
  const getFavoriteRecipes = async () => {
  try {
    const serializedBlue = await AsyncStorage.getItem('favoriteBlue');
    if (serializedBlue !== null) {
      return JSON.parse(serializedBlue);
    }
    return []; // Return an empty array if no Blues are found
  } catch (error) {
    console.log('Error retrieving Bluefavorite Blue:', error);
    return []; // Return an empty array on error
  }
};

const addToBlue = () => {
    if (blueData) {
          console.warn("updatiiiiing");
      const updatedBlue = [...favoriteBlue, BlueData];
      setFavoriteBlue(updatedBlue);

      saveFavoriteBlue(updatedBlue);
      console.warn(updatedBlue);
    }
  };
};

2

Answers


  1. use onClick and not onPress

    </View>
         <View style={styles.infoContainer}>
      <BlueButton
        onClick={()=>  this.addToBlue  }
      />
    
    Login or Signup to reply.
  2. OK so this is a question concerning ReactNative, not React. The title and the tag were misleading.

    You actually never call this.addBlue, you juste returns it on the onPress callback.

    The corrected code shall be:

      <BlueButton
        onPress={()=> this.addToBlue()}
      />
    

    or

      <BlueButton
        onPress={addToBlue} // But doing so will lose the ref of `this`, unless you bind it directly to the function
      />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search