Search code examples
react-nativebridge

Cannot access state outside NativeModules after creating Native Bridge React Native


I am trying to access state outside the results received from NativeModule after creating bridge with native android. Data shows in console.log but cannot accessed outside.

NativeModules["GetapplistModule"].getNonSystemApps(res => {
    var pairs = [];
    for(var key in res){
      var obj = JSON.parse(res[key]);
      pairs.push(obj);
    }
    const [AppData] = React.useState(pairs);
  });

 type AppProps = React.ComponentProps<typeof AppProps>;
 export const notificationTweets: Array<AppProps> = {AppData};

Solution

  • I solved it by using useEffect

    If you are having same problem Wrap your function in useEffect and assign state inside the scope somthing like this.

    const [AppData, setApps] = React.useState([]);
    React.useEffect(() => {
    NativeModules["GetapplistModule"].getNonSystemApps(res => {
        var pairs = [];
        for(var key in res){
          var obj = JSON.parse(res[key]);
          pairs.push(obj);
        }
        setApps(pairs);
      });
    
     type AppProps = React.ComponentProps<typeof AppProps>;
     export const notificationTweets: Array<AppProps> = {AppData};
    }, []);
    

    Now, you can access state anywhere like

    console.log(AppData);
    

    Hope it helps to someone who is dealing with same issue.