Home > OS >  How can i fix this error? ERROR TypeError: null is not an object (evaluating 'userdata.user
How can i fix this error? ERROR TypeError: null is not an object (evaluating 'userdata.user

Time:01-08

How can i fix this error in my project? the error is ERROR TypeError: null is not an object (evaluating 'userdata.user') i am using react native expo after logging into my app and entering mainpage its giving me this error can anyone can help me to fix this error? i today send 8 hours fixing this error but i can't able to fix it can anyone can help me with that?

import { StyleSheet, Text, View, StatusBar } from 'react-native'
import React, { useEffect, useState } from 'react'
import { containerFull } from '../../CommonCss/pagecss'
import { formHead } from '../../CommonCss/formcss'
import Bottomnavbar from '../../Components/Bottomnavbar'
import TopNavbar from '../../Components/TopNavbar'
import FollowersRandomPost from '../../Components/FollowersRandomPost'
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Location from 'expo-location';

const Mainpage = ({ navigation }) => {

    const [userdata, setUserdata] = React.useState(null)
    const [location, setLocation] = useState(null);
    const [errorMsg, setErrorMsg] = useState(null);
    const [city, setCity] = useState(null);
    const [data, setData] =  useState(null)
 
    useEffect(() => {
        AsyncStorage.getItem('user')
            .then(data => {
                // console.log('async userdata ', data)
                setUserdata(JSON.parse(data))
            })
            .catch(err => alert(err))
    }, [])

    console.log('userdata ', userdata)

  useEffect(() => {
        (async () => {
            let { status } = await Location.requestForegroundPermissionsAsync();
            if (status !== 'granted') {
                setErrorMsg('Permission to access location was denied');
            }

            let location = await Location.getCurrentPositionAsync({});
            setLocation(location);

            let city = await Location.reverseGeocodeAsync(location.coords);
            setCity(city[0].city);
        })();
    }, []);


    const sendCity = () => {
        setCity(city);
        fetch('http://192.168.1.52:3000/updateCity', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                city: city,
              username: userdata.user.username
            }),
        })
            .then((response) => response.json())
            .then((data) => {
                console.log('Success:', data);
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    };


    useEffect(() => {
        sendCity();
    }, [])

    return (
        <View style={styles.container}>
            <StatusBar />
            <TopNavbar navigation={navigation} page={"MainPage"} />
            <Bottomnavbar navigation={navigation} page={"MainPage"} />
            <FollowersRandomPost />
        </View>
    )
}

export default Mainpage

const styles = StyleSheet.create({
    container: {
        width: '100%',
        height: '100%',
        backgroundColor: 'black',
        paddingVertical: 50,
    }
})

And why something city value becomes null and something new york which is correct how to fix null?

import { StyleSheet, Text, View, StatusBar } from 'react-native'
import React, { useEffect, useState } from 'react'
import { containerFull } from '../../CommonCss/pagecss'
import { formHead } from '../../CommonCss/formcss'
import Bottomnavbar from '../../Components/Bottomnavbar'
import TopNavbar from '../../Components/TopNavbar'
import FollowersRandomPost from '../../Components/FollowersRandomPost'
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Location from 'expo-location';

const Mainpage = ({ navigation }) => {
  const [userdata, setUserdata] = useState(null);
  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [city, setCity] = useState(null);
  const [data, setData] =  useState(null);

  useEffect(() => {
    async function getUserData() {
      try {
        const userDataString = await AsyncStorage.getItem('user');
        const userData = JSON.parse(userDataString);
        setUserdata(userData);
      } catch (err) {
        alert(err);
      }
    }

    getUserData();
  }, []);

  useEffect(() => {
    async function getLocation() {
      try {
        let { status } = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
          setErrorMsg('Permission to access location was denied');
        }

        let location = await Location.getCurrentPositionAsync({});
        setLocation(location);

        let city = await Location.reverseGeocodeAsync(location.coords);
        setCity(city[0].city);
      } catch (err) {
        console.error(err);
      }
    }

    getLocation();
  }, []);

  useEffect(() => {
    async function sendCity() {
      try {
        setCity(city);
        const response = await fetch('http://192.168.1.52:3000/updateCity', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            city: city,
            username: userdata.user.username
          }),
        });
        const data = await response.json();
        console.log('Success:', data);
      } catch (err) {
        console.error('Error:', err);
      }
    }

    if (userdata) {
      sendCity();
    }
  }, [userdata]);

console.log(city)
  return (
    <View style={styles.container}>
      <StatusBar />
      <TopNavbar navigation={navigation} page={"MainPage"} />
      <Bottomnavbar navigation={navigation} page={"MainPage"} />
    </View>
  );
}


export default Mainpage

CodePudding user response:

You need to wait AsyncStorage to finish his task before using the new data, how about using top lvl await like :

 useEffect(() => {
        await AsyncStorage.getItem('user')
            .then(data => {
                // console.log('async userdata ', data)
                setUserdata(JSON.parse(data))
            })
            .catch(err => alert(err))
    }, [])

    console.log('userdata ', userdata)
  • Related