Unable to handle case of null variable in javascript/react native

I am trying to do something very simple in my react native log in screen. I first try and get the userId of a user and if it’s not set I want to redirect to the user’s login page. When the userId is not set I console out and get a null value for it. But when I create a if statement to check if the userId === null it doesn’t work. Any ideas on what I am doing wrong?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const userId = await AsyncStorage.getItem('userId');
console.warn(userId);
console.warn("When userId is not set I get a value of null");
if (userId === null) {
console.warn("However this check for null is not working");
navigation.navigate("UserLoginWeb");
}
</code>
<code>const userId = await AsyncStorage.getItem('userId'); console.warn(userId); console.warn("When userId is not set I get a value of null"); if (userId === null) { console.warn("However this check for null is not working"); navigation.navigate("UserLoginWeb"); } </code>
const userId = await AsyncStorage.getItem('userId');
console.warn(userId);
console.warn("When userId is not set I get a value of null");
if (userId === null) {
    console.warn("However this check for null is not working");
    navigation.navigate("UserLoginWeb");
}

you cannot use await outside of an async function.
so unless this is the interior of an async function the value of userid is a pending promise

you should either have this code within a async function, although that function also will return a promise.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>async function x(){
const userId = await AsyncStorage.getItem('userId');
console.warn(userId);
console.warn("When userId is not set I get a value of null");
if (userId === null) {
console.warn("However this check for null is not working");
navigation.navigate("UserLoginWeb");
}
}
</code>
<code>async function x(){ const userId = await AsyncStorage.getItem('userId'); console.warn(userId); console.warn("When userId is not set I get a value of null"); if (userId === null) { console.warn("However this check for null is not working"); navigation.navigate("UserLoginWeb"); } } </code>
async function x(){
    const userId = await AsyncStorage.getItem('userId');
    console.warn(userId);
    console.warn("When userId is not set I get a value of null");
    if (userId === null) {
        console.warn("However this check for null is not working");
        navigation.navigate("UserLoginWeb");
    }
}

or you should do something like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>AsyncStorage.getItem('userId').then((userId)=>{
console.warn(userId);
console.warn("When userId is not set I get a value of null");
if (userId === null) {
console.warn("However this check for null is not working");
navigation.navigate("UserLoginWeb");
}
});
console.log("hello");
</code>
<code>AsyncStorage.getItem('userId').then((userId)=>{ console.warn(userId); console.warn("When userId is not set I get a value of null"); if (userId === null) { console.warn("However this check for null is not working"); navigation.navigate("UserLoginWeb"); } }); console.log("hello"); </code>
AsyncStorage.getItem('userId').then((userId)=>{
    console.warn(userId);
    console.warn("When userId is not set I get a value of null");
    if (userId === null) {
        console.warn("However this check for null is not working");
        navigation.navigate("UserLoginWeb");
   }
});
console.log("hello");

an asynchronous function does not block the main code, the code coming after will continue to be executed at the same time as the asynchronous request.
for example the hello in the above code will be executed before/simultaneously with the userid request.
i hope this helps.

This is a common issue with AsyncStorage in React Native. The potential issues here could be:

  • AsyncStorage always returns strings or null. Sometimes it might return the string “null” instead of actual null, which would make === null fail.

  • The check should handle both cases:

    if (userId == null || userId === ‘null’)

  • It’s important to wrap AsyncStorage operations in try-catch blocks since they can fail.

The code below is a proper way to handle this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React, { useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
const CheckUserAuth = ({ navigation }) => {
useEffect(() => {
const checkUserId = async () => {
try {
const userId = await AsyncStorage.getItem('userId');
console.warn('userId value:', userId);
// Correct way to check for null/undefined
if (userId == null || userId === 'null') {
console.warn('User is not logged in');
navigation.navigate('UserLoginWeb');
} else {
console.warn('User is logged in with ID:', userId);
}
} catch (error) {
console.error('Error reading userId from AsyncStorage:', error);
navigation.navigate('UserLoginWeb');
}
};
checkUserId();
}, [navigation]);
return null; // Or your loading component
};
export default CheckUserAuth;</code>
<code>import React, { useEffect } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; const CheckUserAuth = ({ navigation }) => { useEffect(() => { const checkUserId = async () => { try { const userId = await AsyncStorage.getItem('userId'); console.warn('userId value:', userId); // Correct way to check for null/undefined if (userId == null || userId === 'null') { console.warn('User is not logged in'); navigation.navigate('UserLoginWeb'); } else { console.warn('User is logged in with ID:', userId); } } catch (error) { console.error('Error reading userId from AsyncStorage:', error); navigation.navigate('UserLoginWeb'); } }; checkUserId(); }, [navigation]); return null; // Or your loading component }; export default CheckUserAuth;</code>
import React, { useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';

const CheckUserAuth = ({ navigation }) => {
  useEffect(() => {
    const checkUserId = async () => {
      try {
        const userId = await AsyncStorage.getItem('userId');
        console.warn('userId value:', userId);
        
        // Correct way to check for null/undefined
        if (userId == null || userId === 'null') {
          console.warn('User is not logged in');
          navigation.navigate('UserLoginWeb');
        } else {
          console.warn('User is logged in with ID:', userId);
        }
      } catch (error) {
        console.error('Error reading userId from AsyncStorage:', error);
        navigation.navigate('UserLoginWeb');
      }
    };

    checkUserId();
  }, [navigation]);

  return null; // Or your loading component
};

export default CheckUserAuth;

The above code uses proper error handling, handles both null and “null” cases, and wrapped in useEffect to properly handle the async operation. It also includes proper TypeScript/Flow-friendly type checking.

Make sure you’re awaiting the check in a proper async context. If the code is directly in your component body rather than in a useEffect or async function, it won’t work correctly. I hope this helps.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật