Home > Blockchain >  React Native - Unexpected token U in JSON at position 0
React Native - Unexpected token U in JSON at position 0

Time:11-08

I got this error when getting data from an API to my application. I checked in my console and I actually got the token properly but I got this error. I already used AsyncStorage.clear(); at the start of the app

useEffect(() => {
    AsyncStorage.clear();
  });

but the error still show up. I can still get the data even though that error is there so I kinda ignored it for a bit, but now I can't update my data because of the unexpected token.

Home index.js (this is the file trying to get data)

import AsyncStorage from '@react-native-async-storage/async-storage';
import React, {useEffect, useState} from 'react';
import {Image, StyleSheet, Text, View} from 'react-native';
import {Button, Gap, Header} from '../../components';
import {colors, getData} from '../../utils';

export default function Home({navigation}) {
  const [profile, setProfile] = useState({
    name: '',
    email: '',
    phone_number: '',
  });
  const [data, setData] = useState([]);
  const [token, setToken] = useState('');

  useEffect(() => {
    getData('token').then(res => {
      const res_token = res;
      console.log('getting token data response at home: ', res_token);
      setToken(res_token);
    });
    fetch('https://emaillead.aturtoko.id/api/v1/profile', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer${token}`,
      },
    })
      .then(response => response.json())
      .then(json => {
        console.log('token auth: '   token);
        setProfile({
          name: json.user.name,
          email: json.user.email,
          phone_number: json.user.phone_number,
        });
        //setData(json);
        console.log(json);
      })
      .catch(error => console.error(error));
  }, [token]);
  return (
    <View style={styles.page}>
      <Header title="User Data" />
      <Text style={styles.text}>Nama: {profile.name}</Text>
      <Gap height={20} />
      <Text style={styles.text}>Email: {profile.email}</Text>
      <Gap height={20} />
      <Text style={styles.text}>Nomor Telepon: {profile.phone_number}</Text>
      <Gap height={40} />
      <Button
        title="Lihat Campaign"
        onPress={() => navigation.navigate('Campaign')}
      />
    </View>
  );
}

this is the console error message the console   error screenshot

CodePudding user response:

I could not figure out the issue because I need more context, for example, you have called the getData function which is not present in your code.

Anyway, I think you should note the following:

The error you are getting is not necessarily related to the "token" state variable that you are using. This error is usually thrown when JavaScript is trying to parse a malformed JSON string.

For instance, you can reproduce the same error in browser console using the following syntax.

JSON.parse("User") // VM193:1 Uncaught SyntaxError: Unexpected token U in JSON at position 0.

CodePudding user response:

I think the problem maybe be between getData and fetch. You should arrange the order of requests by using await or chain with .then method, or you will have no res_token when you fetch data.

  useEffect(() => {
    getData('token').then(res => {
      const res_token = res;
      console.log('getting token data response at home: ', res_token);
      return res_token
    }).then((res_token) => {
      // do the fetch when res_token is already got
    })
 
  }, []);
  • Related