Having trouble accessing multiple items in JSON format using AsyncStorage in React Native

After attempting to retrieve all items stored in my AsyncStorage, I encountered an issue where the response was not in JSON format. Instead, it was returned in a different format:

 [["engineyard", "{\"login\":\"engineyard\",\"id\":81,\"node_id\":\"MDEyOk9yZ2FuaXphdGlvbjgx\",\"url\":\"https://api.github.com/orgs/engineyard\",\"repos_url\":\"https://api.github.com/orgs/engineyard/repos\",\"events_url\":\"https://api.github.com/orgs/engineyard/events\",\"hooks_url\":\"https://api.github.com/orgs/engineyard/hooks\",\"issues_url\":\"https://api.github.com/orgs/engineyard/issues\",\"members_url\":\"https://api.github.com/orgs/engineyard/members{/member}\",\"public_members_url\":\"https://api.github.com/orgs/engineyard/public_members{/member}\",\"avatar_url\":\"https://avatars.githubusercontent.com/u/81?v=4\",\"description\&\quot;:\"\"}"], ["errfree", "{\"login\":\"errfree\",\"id\":44,\"node_id\&\quot;MDEyOk9yZ2FuaXphdGlvbjQ0\",\"url\":\"https://api.github.com/orgs/errfree\",\"repos_url\":\"https://api.github.com/orgs/errfree/repos\",\"events_url\":\"https://api.github.com/orgs/errfree/events\",\"hooks_url\":\"https://api.github.com/orgs/errfree/hooks\",\"issues_url\":\"https://api.github.com/orgs/errfree/issues\",\"members_url\":\"https://api.github.com/orgs/errfree/members{/member}\",\"public_members_url\":\"https://api.github.com/orgs/errfree/public_members{/member}\",\"avatar_url\":\"https://avatars.githubusercontent.com/u/44?v=4\",\"description\&\quot;:null}"]]

When attempting to retrieve a single item, it returned in JSON format. However, the current format makes it challenging to save in an array for mapping purposes.

Here is the relevant portion of my code:

const getOrgsSaved = async () => {
    let value = []
    try {
        const keys = await AsyncStorage.getAllKeys();
        const Orgs = await AsyncStorage.multiGet(keys)
        return Orgs
    } catch (e) {
        console.log(e)
        return e;
    }
}
// Function to get the items 
const  Main: React.FC = () => {
  const [orgsSave, setOrgsSaved] = useState<Array<Orgs>>([])
  const [orgsData, setOrgsData] = useState<Array<Orgs>>([])

  useEffect(() => {
    loadOrgs()
    getOrgsSaved()
  },[])
  const loadOrgs = () =>{
    Services.getOrgs()
      .then(response =>{
        setOrgsData(response.data)
      
      })
      .catch(e =>{
        console.log(e)
      })
  }
  function getOrgsSaved() {
    Services.getOrgsSaved() // receiving the response here
      .then(response => {
        console.log('get',response)
        setOrgsSaved(response)
      })
 
     
  }
  return (
    <Box flex = {1} >
        <Navbar/>
        <SubHeader/>
        <OrgsList data = {orgsData}/>
        <Footer/>
    </Box>
  );
}

export default Main;

I attempted to use JSON.parse, but encountered this error:

[SyntaxError: JSON Parse error: Unexpected identifier "engineyard"]

Answer №1

The reason for the issue is that your initial item is not formatted in JSON. heroku is being interpreted instead of "heroku".

To prevent this problem, always remember to use JSON.encode when storing string data.
It seems like you are saving the value as-is, which can cause parsing errors.

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

Set the enumeration value to a variable

I am facing a problem where it seems impossible to do this, and I need help with finding a solution enum Vehicles { BMW='BMW', TOYOTA='Toyota' } class MyVehicles { public vehicleName: typeof Vehicles =Vehicles; } const veh ...

Dealing with server-side errors while utilizing react-query and formik

This login page utilizes formik and I am encountering some issues: const handleLogin = () => { const login = useLoginMutation(); return ( <div> <Formik initialValues={{ email: "", password: "" }} ...

Loop through an array of strings

When I receive the data as a string[] https://i.sstatic.net/ttyag.png However, when I attempt to loop over it subUrl(arr) { for(let i of arr) { console.log(i); } } No output is being logged. What could be causing this issue? ...

Encountering an Uncaught Error: MyModule type lacks the 'ɵmod' property

I am currently working on developing a custom module to store all my UI components. It is essential that this module is compatible with Angular 10 and above. Here is the package.json file for my library: { "name": "myLibModule", &qu ...

Use MatDialog to open the next dialog when the previous one has been closed - whether you choose to use a

I'm trying to figure out how to open the next dialog from a stream only after the previous one has been closed. I want to make sure that I don't open all the dialogs in a row as soon as I get the values from the stream. const arraySource ...

How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it. The code below is functioning perfectly: import { relations } from 'drizzle-orm' import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...

Looking to determine if two elements exist within an array? Seeking a boolean result based on their presence

Consider the following array of objects: quesListArray = [ { QuestionTypeID : 1, QuestionTypeName : 'Rating' }, { QuestionTypeID : ...

Create a functioning implementation for retrieving a list of objects from a REST API

I am looking to incorporate an Angular example that retrieves a list from a REST API. Here is what I have attempted: SQL query: @Override public Iterable<Merchants> findAll() { String hql = "select e from " + Merchants.class.getName ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

Separate the date format string into tokens

I am currently attempting to create a function that is able to transform a date format string such as %d/%m/%Y %H:%n where the variables are always denoted by a percentage sign followed by one character, into an array of tokens: ["%d", "/", "%m", "/", " ...

Utilizing ES6, accessing the first element of an array of objects

How can I access the values of the first or a specific object in an array based on an index using ES6? arrayOne =[ { child: [ {e1: 'ABCD', e2: 'BCDF'}, {e1: '1234', e2: '5689'}, {e1: 'QAZ ...

Comprehensive compilation of Typescript error codes along with solutions

Where can I find a comprehensive list of Typescript error codes and their corresponding fixes? I frequently encounter errors during compilation, such as: data_loader_service.ts(10,13): error TS1005: '=>' expected. data_loader_service.ts(10,24 ...

Exploring the power of nesting views using *ngFor in Ionic framework

I am looking to design a screen that features nested views using the *ngFor loop. The data I have is in a two-dimensional array format and I want to iterate through it to display the same view for each row within each section. It should look something like ...

Encountering issues with Typescript Intellisense not functioning properly with root directory imports specified with the @

I am facing a challenge where TypeScript/Intellisense is unable to determine types when importing using the @ symbol with my compilerOptions set to the root directory: https://i.sstatic.net/1PgBI.png When I use ../, types are visible clearly: https://i. ...

Having trouble running `npm start` on my NodeJs project

Hi everyone, I could really use some help with the npm start command. I am currently working on a Node.js project with TypeScript on Windows 7-64, but I'm encountering errors when trying to start it. If you can assist, please check out the following ...

Mocking multiple services and their constructors in an Angular 2 TypeScript Jasmine test component

I've got this login component code snippet that I need help testing in Angular. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FormBuilder, FormGroup, Validators } from '@ ...

What is the best way to pinpoint and eliminate a Subject from an Observable?

Currently, I am utilizing a service to gather user responses from a questionnaire. The sequence of events is outlined below: questionnaire.component.ts : serves as the main container that receives data from question.service.ts question-shell.component.ts ...

What is the best method for dividing a user interface into several arrays of keys, each grouped by type?

Given a simple structure: structure IPerson { firstName: string; lastName: string; age: number; city: string; favoriteNumber: number; isMarried: boolean; hasDriverLicense: boolean; } How do I create arrays containing keys grouped by data typ ...

What is the best way to determine if several simultaneous tasks have been completed?

Implementing multiple parallel actions in an Angular component has proven to be challenging for me. Following each action (foo), I subscribe to its result. I've been attempting to determine if any actions are currently running or have completed using ...