Encountered a surprising issue in JSON parsing with React Native - Unexpected character 'U' at

I encountered an error while retrieving data from an API for my application. Despite successfully obtaining the token, an unexpected error still occurred, even after using AsyncStorage.clear() at the beginning of the app.

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

Although the error persists, I am still able to retrieve data. However, the issue prevents me from updating the data due to the unexpected token.

Here is the code snippet from Home index.js (the file attempting to retrieve 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}>Name: {profile.name}</Text>
      <Gap height={20} />
      <Text style={styles.text}>Email: {profile.email}</Text>
      <Gap height={20} />
      <Text style={styles.text}>Phone Number: {profile.phone_number}</Text>
      <Gap height={40} />
      <Button
        title="View Campaign"
        onPress={() => navigation.navigate('Campaign')}
      />
    </View>
  );
}

For more details, you can refer to the console output and error message here

Answer №1

It seems like the issue might lie between the getData and fetch functions. Make sure to properly order your requests using await or chain with .then method to avoid encountering the issue of missing res_token when fetching data.

  useEffect(() => {
    getData('token').then(res => {
      const res_token = res;
      console.log('Obtaining token data response at home: ', res_token);
      return res_token
    }).then((res_token) => {
      // Perform the fetch once res_token is obtained
    })
 
  }, []);

Answer №2

The issue at hand has left me puzzled as I require additional context to fully grasp it. It seems that you have referenced the getData function, which appears to be missing from your code.

Nevertheless, it is worth noting the following points:

The error message you are encountering may not necessarily be caused by the "token" state variable you are utilizing. Typically, this error occurs when JavaScript attempts to parse an improperly formatted JSON string.

For instance, you can trigger a similar error in the browser console by using the following syntax:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing AJAX in Rails for the new/create action can greatly enhance the user

I have a timeline with event sections on it that allow you to create, view, update, and delete events directly on the timeline page. Currently, the functionality for deleting an event is working smoothly as the delete section refreshes along with the timel ...

Exporting State From Another ReactJS Module: A Step-by-Step Guide

A new project is underway with 3 students who are diving into the world of React for the first time. To make our work more efficient, I suggested dividing the code so that each student could work on a different aspect simultaneously. However, when I attemp ...

Combining array elements based on shared field using JQ

I am trying to merge two arrays with unique EMAIL values. Here are the arrays: First Array: [ { "EMAIL": "uniqueEmail1", "INUSE": "1" }, { "EMAIL": "uniqueEmail2", "INU ...

Next JS encountered an error - Error [ERR_HTTP_HEADERS_SENT]: It is not possible to set headers after they have already been sent to the

Having crafted a serverless application using next.js, Vercel, and Google Sheets to store customer contact data, I encountered an issue post-deployment. While my application works flawlessly locally, after deployment, I started receiving the following erro ...

Obtain precise JSON information using Node.js

Having limited experience with Angular JS and Node JS, I find myself in need of assistance. On the server side, I have multiple JSON files containing language translations. Based on a client's request for a specific language, such as French, I must re ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

Issue: Unable to open port (GetCommState) : Error code 1 not recognized - Utilizing Nodejs, express, SerialPort

I am currently attempting to establish a connection between a fiscal printer with serial input and nodejs. I am utilizing the SerialPort module, but encountering difficulty in establishing the connection. The console is displaying the following error messa ...

Connecting AngularJS with select options

I am currently developing a checkout feature that calculates shipping prices based on the selected country. If the user picks United States, it should display US. For any other country selection, it should show Not US While the shipping function correctly ...

What is the best way to transfer data from a component to a .ts file that contains an array?

I am currently developing a budgeting application and I have a component that is responsible for holding values that I want to pass to an array stored in a separate file. While I can retrieve data from the array, I am facing difficulty in figuring out how ...

How do React Native proxies differ from vanilla React proxies in their functionality?

Trying to retrieve data from an API running locally on port 5000 of my device, I recalled setting the proxy in package.json when working on React web applications: "proxy": "https://localhost:5000" Attempting to fetch information f ...

Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls. Recently, I have been introduced to ASP.NET controls and the overall environment. I am curious about the correct method for handling ajax requests when they n ...

Showing image URL data fetched in JSON format using AJAX library JQuery

I am using Ajax to retrieve data from the database in JSON format. I am able to retrieve various data fields successfully, but I am facing an issue with displaying an image. Although I can see the image URL in the JSON response, the image is not being disp ...

Colorbox: Display a specific section from a separate HTML page

Currently, I am facing a challenge where I need to open just one specific part of an external HTML page in a colorbox. I attempted the following approach, however it is opening the entire page instead of just the specified part (at the div with id="conten ...

Tips for determining if an HTMLElement has already been created

One issue I'm facing is with a third party component that emits an "onCellEdit" event and passes a cell element as a parameter. My goal is to automatically select the entire text in the input element generated inside this cell when the event occurs. ...

Incorporating a hyperlink into an Iframe triggered by Fancybox2-AJAX, specific to the Iframe's unique identifier

One thing I have noticed is that everything seems to be working fine up until the point where I try to load it through fancybox via AJAX. An example of it working statically: <iframe id="videourl1" width="640" height="340" src="" frameBorder="0">& ...

Is there a way to apply a consistent border to both the input radio button and its corresponding label once the radio button has been selected

CSS: <div class="form-check fs-3 mb-3"> <input id="first_question" name="first_question" type="radio" value="n"> <label for="first_question">no</label> </div> Is ...

Firefox: repeated occurrences of style sheet in developer tools

I am currently managing a sample website with multiple linked style sheets at . One of these style sheet links needs to be toggled on and off, hence it includes a unique id: <link id="sketch" rel="stylesheet" type="text/css" ...

Utilize the .not() filter function in JavaScript

I am trying to apply a filter of not(.pseudo-element) using JavaScript, but I am unsure how to add it. So far, I have been able to extract #app from the DOM with the following code: const app = document.getElementById('app') app.style.filter ...

What is the best way to convert a JSON list into a Python list?

When I print my json data using the code below, it shows all the items in my emailList: print(data['emailList']) This is the output: [ { 'emailId': 987654321, 'customerId': 123456789, }, { 'emailId': 56789 ...

Utilizing the navigator object in React Navigator and expo to enhance component functionality

My React Native application requires a redirection on a specific component. Within my main App.js component, I have the following code snippet: import React from "react"; import { Text } from "react-native"; import { createAppContainer } from "react-nav ...