Home > Enterprise >  How to create object of user data in React native?
How to create object of user data in React native?

Time:01-04

I was trying to save a user profile (name, age, gender,...) by using AsyncStorage in the app. I just was able to save eihter one of the inputs, not all of them. Is anybody knows how to create an object of user data from TextInput (function component)?

CodePudding user response:

You can JSON.stringify the object into the AsyncStorage and then JSON.parse the value whenever you want to get the object from the AsyncStorage.

AsyncStorage.setItem(data, JSON.stringify(data), (err)=> {
    if(err){
        console.log("an error");
        throw err;
    }
    console.log("success");
}).catch((err)=> {
    console.log("error is: "   err);
});

And then receive it like,

try {
    const value = await AsyncStorage.getItem(data);
    if (value !== null) {
        // We have data!!
        console.log(JSON.parse(value));
    }
} catch (error) {
    // Error retrieving data
}

Now if you want to know, how to store data as an object from TextInput, there are multiple ways. One of them is using useState.

const [userData, setUserData] = useState({
name: '',
age: 0,
gender: '',
...
});

Then once you get the value from TextInput for any input save it as,

setUserData(prev => ({
            ...prev,
            ['name']: textInputName,
}))

CodePudding user response:

that's simple . at first you can define one object in state like this:

const [myUser,SetMyUser]= useState({
name:"",
age:0,
gender:"",
});

and set each of item in text input like that:

SetMyUser(prev => ({
            ...prev,
            ['name']: txtName,
}))

after that you can save that in AsyncStorage or send to your `server.

  • Related