-1

I save an object containing user data like email, username, etc.

I used AsyncStorage to save them, and when I get them I just see a string when I log or use it in my textInput so how to handle this and just get a specific data like Just Email or Just Username I saved?

My Code

Sign Up

 const {
      username,
      email,
      city,
      mobileNumber,
    } = this.state;

  const profileData = {
        "username": username,
        "email": email,
        "city": city,
        "mobileNumber": mobileNumber
      }
 firebase
        .auth()
        .createUserWithEmailAndPassword(email, password)
        .then(async user => {
          firebase
            .database()
            .ref(`users/${user.user.uid}`)
            .set({
              username: username,
              type: type,
              email: email,
              city: city,
              mobileNumber: mobileNumber,
              token: fcmToken
            });
          this.props.navigation.navigate("Home");
          await AsyncStorage.setItem('@MyProfile:data', JSON.stringify(profileData)).then(() => console.log("Saved"));
        }).catch(err => console.log(err));

Profile Screen

async componentDidMount() {
        try {
            await AsyncStorage.getItem('@MyProfile:data')
                .then(data => this.setState({ data }))
                .catch(error => console.log('@error' + error));

                console.log(this.state.data); // 
        } catch (error) {
            console.log("@CError", error);
        }
    }

render(){
return(
   <View style={styles.logoSection}>
                                {/* <SvgComponent height={100} /> */}
                                <Icon name="ios-contact" size={90} color='#4d8dd6' style={{ marginTop: 9 }} />

                                <Text style={{ fontSize: 18, color: "#000", margin: 35, marginTop: 7 }}>{this.state.data}</Text> // i wnat just display username here from storage
                            </View>
)
}

Console

  console.log(this.state.data); 

As a string i think: {"username":"user","email":"user@user.us","city":"usercity","mobileNumber":"0597979979"}

DevAS
  • 807
  • 2
  • 15
  • 41
  • I don't see the issue? Just JSON.parse(this.state.data) to get back into an object. – basic Jun 04 '19 at 18:50
  • @basic please add that as answer – Junius L Jun 04 '19 at 18:51
  • 3
    Possible duplicate of [Parse JSON in JavaScript?](https://stackoverflow.com/questions/4935632/parse-json-in-javascript) – Randy Casburn Jun 04 '19 at 18:53
  • 2
    @JuniusL. I'd rather close it as a dupe than add an answer for the same old thing. – basic Jun 04 '19 at 18:56
  • Ok that's right but when i display these `JSON.parse(this.state.data.username)` in my i got an error " Cannot read property 'username' of undefined " – DevAS Jun 04 '19 at 18:58
  • @DevAS you don't parse down to the key. Parse the actual obj and then extract the key. var json = JSON.parse(this.state.data); var username = json.username; – basic Jun 04 '19 at 18:59
  • that's work in the componentDidMount() when i log it, but when i render them in a Text i got the previews error :/ `await AsyncStorage.getItem('@MyProfile:data') .then(json => JSON.parse(json)) .then(data => this.setState({ data })) .catch(error => console.log('@error' + error))` , Render() ` {this.state.data.username}` – DevAS Jun 04 '19 at 19:08
  • OH Work now, I'm not declaring data in this.state={}, I just think when i set state a data it will be declared and i can use them. any idea about it? – DevAS Jun 04 '19 at 19:19

1 Answers1

0

{this.state.data.username} or {this.state.data['username']}

But probably in this line inside {this.state.data} you wont have username access in the first render, probably this.state.data will be empty so you need to validate before use this.state.data['username']!

  • I'm validating them when the user signs up I save them to the storage, now I have some issue when the user logout I use asyncStorage.clear() in logout function, now when he sign in again and go to his profile he will get an error because of the storage is empty, and the storage step work when he sign up, so how to handle this? – DevAS Jun 08 '19 at 17:34
  • What error occurs? If is because you don't have access of username, you need to check before access de prop! Like if(this.state.data) this.state.data['username'] – Mauricio Carlezzo Jun 11 '19 at 12:04
  • Error, it's because It's removed the storage when logging out, I didn't understand what do you mean of this.state.data['username '] why I do that and where? – DevAS Jun 11 '19 at 17:55
  • TypeError: TypeError: Cannot read property 'username' of null – DevAS Jun 12 '19 at 15:29
  • I know it's because the username is empty cuz I'm clear the storage and check it firstly like`if(this.state.data){ .. put my elements .. } else { // what i should do here? }`, I think it's not friendly to our users – DevAS Jun 12 '19 at 15:36
  • Or Don't use `AsyncStorage.clear()` in logout function? – DevAS Jun 12 '19 at 15:40
  • @DevAS probably this page won't show if you clear the storage, so in ` like if(this.state.data){ .. put my elements .. } else { // here you can return an empty view } ` Just for prevent the error and the method render! If this is your goal, if not, you can describe more your goal if the storage is empty, what you want to do? – Mauricio Carlezzo Jun 12 '19 at 16:22
  • actually, I don't know :D, I don't want to increase the app size so for that I want to clear the storage after a user logout, OR it does not relations between `AsyncStorage` with app size? – DevAS Jun 12 '19 at 16:44
  • don't worry, it will increase user data size, but the data that you print is very small, and every time when you sign in and use AsyncStorage.setItem '@MyProfile:data' the data will override {"username":"user","email":"user@user.us","city":"usercity","mobileNumber":"0597979979"} – Mauricio Carlezzo Jun 12 '19 at 16:59
  • That's fine, If you have time check This Q, https://stackoverflow.com/questions/56567904/handle-call-functions-with-async-and-await – DevAS Jun 12 '19 at 18:41