javascriptjsonreact-nativeapi

Output one json record react native


I have an api request that contains 1 json record, how can I display it on the screen?

 const [user, setUser] = useState();
   const getUserData = async () => {
    // {headers: {Authorization: "Basic " + base64.encode(username + ":" + password),}}
    try {
      const response = await fetch('http://*******/warrant/' + route.params.id, {headers: {Authorization: "Basic " + base64.encode(username + ":" + password),}});
      json = await response.json();
      
      setUser(json.warrant);
    } catch (error) {
      console.error(error);
    }
  };



useState(() => {
    getUserData();
  }, []);

 return (
    <View >
      <View >
        <Text style={styles.input2}>name:</Text>
      <Text style={styles.input} value={user.name}>{user.name}</Text>
      </View>

Error: undefined is not an object (evaluating 'user.name')

json example:

{"warrant": {"dateend": "1", "datestart": "1", "description": "1", "fio": "1", "id": 2, "image": "", "name": " 3", "number": "4", "numberitem": "4", "state": 2}}

Solution

  • When you write const [user, setUser] = useState();, you're calling useState with an empty argument. That means user is undefined by default, and unsafe to access. There are two easy solutions to this:

    1. safely access the name property: user?.name instead of user.name
    2. assign a default object to user: const [user, setUser] = useState({});

    For more see: