1

I'm asking you this question because an error occurred again. We're now receiving data through axios and storing that data through useState(). So if you create it on the screen and render it right away, you can see the data, but if you go to the previous page and go back in, an error occurs. Please let me know how to solve it. my Error TypeError: undefined is not an object (evaluating 'userInfo._name')

my Code

import React, { useState, useEffect } from "react";
import { withNavigation } from "react-navigation";
import { Text, View, StyleSheet, SafeAreaView, Image } from "react-native";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from "react-native-responsive-screen";

import axios from "axios";
const MyPage = ({ navigation, info }) => {
  const [userInfo, setUserInfo] = useState();
  const getData = async () => {
    try {
      axios
        .get(
          "http://everyweardev-env.eba-azpdvh2m.ap-northeast-2.elasticbeanstalk.com/api/v1/user"
        )
        .then((res) => res)
        .then((data) => {
          setUserInfo(data.data.data.result);
        })
        .catch((err) => console.log(err));
    } catch (error) {}
  };
  useEffect(() => {
    const unsubscribe = navigation.addListener("focus", () => {
      getData();
    });
    return unsubscribe;
  }, [navigation]);

  return (
    <View>
      {/* <Image source={require("../../images/profile.png")} /> */}
      <Text>{userInfo._name}</Text>
      <Text>{userInfo._mail}</Text>
    </View>
  );
};

export default withNavigation(MyPage);
byungju
  • 69
  • 1
  • 5

1 Answers1

1

The problem is happening in the initial render where the userInfo object is null.

Do something like below, where you access the property only when there is a value for userInfo

  <Text>{userInfo?._name}</Text>
  <Text>{userInfo?._mail}</Text>
Guruparan Giritharan
  • 15,660
  • 4
  • 27
  • 50
  • Thank you. I solved it right away with your solution. But if I have one question, may I know what the question mark means? – byungju May 04 '21 at 12:46
  • Its basically a null check like if userInfo has a value then get the name property of it, you can get detailed description in this question https://stackoverflow.com/questions/32139078/null-safe-property-access-and-conditional-assignment-in-es6-2015 – Guruparan Giritharan May 04 '21 at 12:48
  • Thank you for the good information. Have a good day. – byungju May 04 '21 at 12:53