Skip to content
Advertisement

Parsing JSON object with AsyncStorage

I am basically trying to write and read a simple object.

Writing: AsyncStorage.setItem('@Test', JSON.stringify(newStudent)) Reading: console.log(JSON.parse(AsyncStorage.getItem('@Test'))) But im getting “Uncaught SyntaxError: Unexpected token o in JSON at position 1”.

I Also tried console.log(AsyncStorage.getItem('@Test').ID) But im getting “Undefined”.

How can I parse the object?

Advertisement

Answer

There are two ways you can get your information from AsyncStorage

First:

const retriveData = async () => {
    const value = await AsyncStorage.getItem("@Test");
    return JSON.parse(value)
}

Then you can simply call the function and catch the value in a variable

var test = retrieveData();

Second:

If you do not want to use an async function. You can create a hook that stores thaat will store the value of the variable and then update the value like so:

const [testValue, setTestValue] = useState(null);
AsyncStorage.getItem("@Test").then((value) => { setTestValue(value) });

Make sure that you are importing AsyncStorage this way:

import {AsyncStorage} from "react-native";

And not this way:

import AsyncStorage from "react-native";

If you need additional information about AsyncStorage look at the docs here.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement