Skip to content
Advertisement

How to implement multiple functions on a single event handler?

I have this simple react native app that on button click it redirects user to a page. I’m saving data in a cache so that if user clicks the store button it stores data and after refresh it sets store data. However, I would like to implement this logic on a single button, not on 2 different buttons as it is now. Can someone explain me how could I achieve this?

export const App = () => {
  const [showFirstWeb, setFirstWeb] = useState(false);

  const getData = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem("@web_Key");
      return setFirstWeb(JSON.parse(jsonValue));
    } catch (e) {
      console.log("error", e);
    }
  };

  useEffect(() => getData, []);

  const storeData = async () => {
    try {
      const jsonValue = JSON.stringify(showFirstWeb);
      await AsyncStorage.setItem("@web_Key", jsonValue);
    } catch (e) {
      console.log("error", e);
    }
  };

  return (
    <View>
      <View style={styles.buttonStyle}>
         <Button onPress={setFirstWeb(!showFirstWeb)}/>
         <Button onPress={storeData} title="store"/>
      <View>
        {showFirstWeb && <MyWebComponent uri="https://www.google.com/" />}
      </View>
    </View>
  );
};

const MyWebComponent = (uri) => {
  return <WebView source={uri} />;
};```

Advertisement

Answer

export const App = () => {
  const [showFirstWeb, setFirstWeb] = useState(false);

  const getData = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem("@web_Key");
      return setFirstWeb(JSON.parse(jsonValue));
    } catch (e) {
      console.log("error", e);
    }
  };

  // you forgot to call the function here
  useEffect(() => getData(), []);

  const storeData = async () => {
    try {
      // get the new value
      const newShowFirstWeb = !showFirstWeb
      // use the new value
      setFirstWeb(newShowFirstWeb)
      const jsonValue = JSON.stringify(newShowFirstWeb );
      await AsyncStorage.setItem("@web_Key", jsonValue);
    } catch (e) {
      console.log("error", e);
    }
  };

  return (
    <View>
      <View style={styles.buttonStyle}>
         <Button onPress={storeData} title="store"/>
      <View>
        {showFirstWeb && <MyWebComponent uri="https://www.google.com/" />}
      </View>
    </View>
  );
};
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement