React Native threw an error: Unexpected Token "o" found in JSON at position 1 when using AsyncStorage

I'm feeling lost and frustrated after trying numerous solutions. I can't seem to figure out why I keep getting this error while attempting to read from asyncstorage in React Native. I know that in order to retrieve asyncstorage as a string, I need to parse it, but I'm continuously encountering this particular type of issue.


class AddScreen extends React.Component {
  constructor(props) {
    i = 0;
    super(props);
    var text = {};
    this.state = {text: ''};
  }

  setName = (text) => {
    text.name = text;
    var name = ("name"+i++);
    AsyncStorage.setItem(name, text);

    this.setState({name: text});
    var booga=  AsyncStorage.getItem(name);
    var booga1 = JSON.parse(booga);
    alert(booga1);
  }

  render() {
    return (
      <View style={{flex: 1, alignItems: "center", justifyContent: "center"}}>
        <TextInput
          style={{height: 100}}
          placeholder="Name of expense"
          onChangeText={this.setName}
        />
        <View style={{width: 50, height: 100}} />
        <Text>Add Screen</Text>
      </View>
    );
  }
}

When running the app on my device using Expo, I encounter the following error:


Unexpected token o in JSON at position 1
Object.AddScreen._this.setName [as onChangeText]
App.js:26:20
Object._onChange
TextInput.js:1252:42
Object.invokeGuardedCallbackImpl
ReactNativeRenderer-dev.js:93:9
invokeGuardedCallback
ReactNativeRenderer-dev.js:318:30
invokeGuardedCallbackAndCatchFirstError
ReactNativeRenderer-dev.js:342:24
executeDispatch
ReactNativeRenderer-dev.js:715:2
executeDispatchesInOrder
ReactNativeRenderer-dev.js:737:4
executeDispatchesAndRelease
ReactNativeRenderer-dev.js:894:4
executeDispatchesAndReleaseTopLevel
ReactNativeRenderer-dev.js:902:9

Answer №1

Why do you invoke the async storage function for every change in the characters? This approach is not recommended. It would be more appropriate to call the async storage within the componentDidMound() method. Then, you can write to async storage on button click or any other suitable event.

//method to read from async storage
readData() {
   AsyncStorage.getItem("LOGED_CREDENTIALS").then(value => {
      if (value) {
        let data = JSON.parse(value);
        // your code here...
      } else {
        //handle error...
      }
   });
}

//method to write data
setData(data){
  AsyncStorage.setItem(
     "LOGED_CREDENTIALS",
     JSON.stringify(data)
  );
}

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

Issues arise when using res.send() with ExpressJS and Mongoose

Initially, I have multiple callbacks that need to be executed before sending a res.send() to construct a JSON API: app.get('/api', function (req, res){ ... function logPagesId() { console.log("load: " +pagesId); c ...

How can you create a custom column button in a SharePoint library that is only visible when the file type is a "Folder"?

A unique custom button column is being created (Test) The goal is to conditionally show the button only when the file type is a folder. The JSON code provided below was intended for this purpose, but it seems to be not functioning as expected. { " ...

Issue with Jquery UI draggable positioning in a specific Reveal.js slide

While my jQuery draggable feature works flawlessly in a simple HTML page without the presence of reveal.js, I encounter an issue within my reveal.js presentation where I utilize embed=true [utilizing only a portion of the full page for each slide]. When i ...

Is it considered safe to modify variables by using this[varName] = something within a function that includes varName as a parameter?

As I continue working on this function, a question arises regarding the safety of changing variables in this manner. In my Angular service, I utilize utility functions where context represents this from the component calling the function. The code snippet ...

The error message is indicating that the property `match` is being attempted on an undefined object. This issue is puzzling as it does not reference any specific files or

I encountered an issue while working on my project: I kept receiving the error message "Cannot read property match of undefined." Cannot read property 'match' of undefined The error points to a specific line in polyfills.js: process.version.ma ...

Transform the jquery array into JSON format and transmit it via ajax communication

My array looks like this info['mk'] = 'hi'; info['pk'] = 'hello'; info['wk'] = 'hi'; info['rk'] = 'hello'; Can I convert it to JSON and send it using AJAX? ...

Is your FontAwesome icon appearing oversized?

While working on , I noticed a discrepancy in the header design compared to . The elements "#navigation ul.nav > li a" seem to be wider on the former site than on the latter, despite my efforts to replicate the styles precisely. Upon further inspectio ...

Passing the value emitted from the vue-multiselect.js component to the main view

I am trying to pass data from my MultiSelectFilter component to my Home.vue view, but I am not seeing any results when using console.log. Even after checking the documentation on using the @input event for capturing changes in selection (), I can't se ...

Is there a way to format this into four columns within a single row while ensuring it is responsive?

I am working on a layout with a Grid and Card, aiming to have 4 columns in one row. However, the 4th column ends up in the 2nd row instead, as shown below: https://i.sstatic.net/gOeMm.png My goal is to align all 4 columns in a single row. Additionally, w ...

Choose all the inputs with the value attribute specified

How can I select all input textboxes in my form that have the required class and no value using jQuery? Currently, I am using: $('input[value=""]', '.required') The issue I am facing is that even when a user enters a value in the text ...

"Unlocking the Potential: Maximizing the Benefits of the top.gg Vote Web

My bot has been verified on top.gg, and I'm looking to offer rewards to users who vote for my bot. How can I detect when someone votes for my bot, get their ID, check if it's the weekend, and take action after the vote? Essentially, how do I util ...

Using Python to navigate JSON files containing multiple arrays

When attempting to extract data from a JSON file and transform it into an object type, I encountered multiple arrays of latitudes and longitudes. How can I handle this using Python? Snippet of Python code* import os from flask import Flask, render_templat ...

Securing JSON data using an authentication token

My Rails application sends requests via posts and receives responses in JSON format. However, the line below seems to be causing an issue: protection_from_forgery with: :exception It's preventing me from processing the request. I came across a sugge ...

I'm curious if there is an uncomplicated method to host a JSON file that is both readable and updatable within the Google Cloud Platform

My goal is to host a JSON document that will act as a hosted version of json-server. While I could use My JSON Server for this purpose, I am opting to transition my architecture to GCP and want to become more familiar with it. Initially, I explored the St ...

Encountering issues while trying to modify a JSON file using Python

My goal is to eliminate the array containing "Nike" under the "Shoe" variable. Below is the Json file I am working with: { "Shoes/Colorways": [ { "Shoe": "Nike", &q ...

A way to verify a datalist field using jQuery validator within a PHP environment

Greetings, I currently work as a web application developer and I am facing an issue with jQuery validation. I have a form where I need to display a list of employees using the `datalist` tag. The client should be able to enter a correct name or select an e ...

Having trouble passing multiple associative array values from JavaScript/AJAX to PHP

We have been encountering an issue when trying to pass multiple associative array values from JavaScript/AJAX to PHP, as the PHP file is receiving an empty object/array. Could someone kindly assist us in retrieving the values of an associative array from ...

Discovering all mongoDB documents utilizing geolocation can be achieved by implementing specific queries that target

Utilizing the react geosuggest package, I am saving event locations in MongoDB. The data retrieved from Google Places gets stored in this format each time: "_id": "vvagbSbEginyrQGK8", "name": "test3", "googleLocation": { "label": "Testaccio, Roma, Ita ...

What is the method for transforming a portion of text from a website into HTML elements?

Currently, my workflow involves copying text from a webpage and then extracting the html tags. I go through the process of selecting the text, visiting wordtohtml.net, pasting it there, and finally copying the output with the necessary html tags and class ...

What causes Next.JS to automatically strip out CSS during the production build process?

Encountering unpredictability in CSS loading while deploying my Next.JS site. Everything appears fine locally, but once deployed, the CSS rules seem to vanish entirely. The element has the attached class, yet the corresponding styling rules are nowhere to ...