How To Display Wifi List Promise Values React Native

I’m using the react-native-wifi-reborn package to get a list of all nearby wifi points. How do I get the list out of the promise? I’ve looked at one solution and it uses a class, but where my app calls the function to get the list, it isn’t in one.

const MainScreen = ({navigation}) => {

    requestFineLocationPermission();

    WifiManager.setEnabled(true);
    let wifiList = WifiManager.reScanAndLoadWifiList().then((data) => {return data});

    console.log(wifiList);

    return (

        <Layout style={styles.container}>
                
                ......

        </Layout>
    );
}

export default MainScreen;

When wifiList is logged, the output is {"_U": 0, "_V": 0, "_W": null, "_X": null}

26 thoughts on “How To Display Wifi List Promise Values React Native”

  1. This is a case of a React functional component, which is an simpler way to define a React components compared to using classes. See more info in the docs.

    In your case, your component not being updated and re-rendered with the new wifiList data, because in your current code, you are not updating the component state at all:

        let wifiList = WifiManager.reScanAndLoadWifiList().then((data) => {
          return data
        });
    

    In this case, you are returning data result in a promise, but you are not using it to update the component state, and you aren’t using await neither to retrieve the promise result. So you are actually assigning a Promise reference to wifiList, not the promise data result.

    To correctly update the state on a functional component, you can use the React hook useState().

    The result would look something like:

    const MainScreen = ({navigation}) => {
    
        requestFineLocationPermission();
    
        const [wifiList, setWifiList] = useState(/* initialValue */); // you may provide an initial value (optional, defaults to undefined)
    
        WifiManager.setEnabled(true);
        WifiManager.reScanAndLoadWifiList().then((data) => { 
          // update the state here
          setWifiList(data);
        });
    
        // this will log the initialValue 'undefined' the first time, 
        // then after state is is updated, 
        // it will log the actual wifi list data, resolved by 'WifiManager.reScanAndLoadWifiList()'
        console.log(wifiList);
    
        return (
    
            <Layout style={styles.container}>
                    
                    ......
    
            </Layout>
        );
    }
    
    export default MainScreen;
    
    Reply

Leave a Comment