Search code examples
reactjsasynchronoususe-effectrestasyncstorage

React Native - I want to set my session state first before I call my API


I am new to React Native. If someone can help me then would be great.

How I can set my session state first from AsyncStorage before it goes for API call. Because this API call required sessionId (UserId) so it can return only those data which belong to this userId.

The issue I am currently facing is when API calls for the data it is calling with null seesionId instead of some value which I am getting from AsyncStorage because both methods (settingSession, InitList ) are async.

const [sessionId, setSessionId] = useState(null);

const settingSession = async () => {
  await AsyncStorage.getItem('userId').then(val => setSessionId(val));
}

 useEffect(() => {
    settingSession(); // Setting sessionId
    InitList(); // Calling API which required session value
   
}, []);

const InitList = async () => {

    var requestOptions = {
        method: 'GET',
        redirect: 'follow'
    };

    try {
        // getting sessionId null instead of value from AsyncStorage
        const response = await fetch("http://127.0.0.1:8080/skyzerguide/referenceGuideFunctions/tetra/user/" + sessionId, requestOptions)
        const status = await response.status;
        const responseJson = await response.json();
        
        if (status == 204) {
   
            throw new Error('204 - No Content');
        } else {
            setMasterDataSource(responseJson);
        }

    } catch (error) {
        console.log(error);
        return false;
    }
}

Solution

  • I'm thinking of two possible solutions:

    1. Separate InitList() into a separate useEffect call, and put sessionId in the dependency array, so that the API call is only made when the sessionId has actually been updated:
    useEffect(() => {
        settingSession(); // Setting sessionId
    }, []);  
    
     useEffect(() => {
        InitList(); // Calling API which required session value
    }, [sessionId]);
    
    1. Wrap both functions in an async function within the useEffect call, and call them sequentially using await:
    useEffect(() => {
        const setSessionAndInitList = async() => {
            await InitList(); // Calling API which required session value
            await settingSession(); // Setting sessionId
        }
        setSessionAndInitList()
    }, []);  
    

    Let me know if either works!