skip to Main Content

I need to call the api only when we back from the next screen to previous screen and it should not be called on the first time when we go to the screen in react native.

2

Answers


  1. The approach I use in such situations is to pass a route param that would trigger that particular api on the parent screen. I am assuming you are using React Native Navigation V6. In that case the child would have code like this:

    navigation.navigate('parentScreenName', {callAPI: true})
    

    and in your parent element the code will look like:

    const parentElement = ({navigation, route} : parentElementProps) => {
    const callAPI = route.params?.callAPI;
    if(callAPI){
    // do api call 
    }
    //rest of your code
    }
    

    So when you land on this screen from anywhere else then the callAPI is undefined and so the api call wont trigger but when you navigate back from the child screen then the api is triggered because callAPI is true and you get your results.

    Login or Signup to reply.
  2. You can pass params from your 2nd screen like ,

    //Back Button Functionality
    const okHandle = (FromScreen ) => {
        navigation.navigate("Settings", { FromScreen });
      };
      
     
     //UI for your back button
      <Button okHandle={() => okHandle("FromSecondScreen")} />

    And in the first screen you can do it like this using useEffect hook,

      useEffect(() => {
        if (FromScreen === "FromPreviousScreen") {
         //Whatever function you can call here.
          };
        }
      }, [FromScreen]);

    This useEffect will be called

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search