'React-Native: Save data to AsyncStorage?

Hello I'm trying to save data into AsyncStorage after logging in to application, but Im not quite sure where to implement the Asyncstorage syntax? Asyncstorage Documentation I know that I somehow have to convert the object into a string (JSON.strinify) and then add the code lube somewhere around where I get the response.

const LoginForm = ({navigation}) => {
  
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(false);


    async function handleSubmit(){
    const headers = await getUserToken() //'profile'
    //console.log(headers, 'getusertoken')
    const data = { email, password };
    console.log(data, 'this is dataa')
    
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json",

      ACCEPT: 'application/json', },
      body: JSON.stringify(data)
    };
  
    fetch("API_HERE/auth/sign_in", requestOptions)
      .then(response => console.log(headers.response)
        //console.log(response.headers, 'response'),
        )
      
      //.then(res => console.log(res));
      //setEmail(true)
      //setPassword(true)
      setIsLoggedIn(true)
        if(setIsLoggedIn){
        return navigation.navigate('ProfileLanding')  
        }  
    }


 

  return (

      <SafeAreaView style={styles.container}>
      <ScrollView>
        <View style={styles.loginBar}>
            <Text style={styles.loginTitle}>Login to my app</Text>
              <View className="login-form">
                <TextInput
                  className="login-info"
                  style={styles.input}
                  id="id"
                  onChangeText={(text) => setEmail(text)}
                  type="text"
                  placeholder="[email protected]"
                  value={email}/>
                <TextInput
                  className="login-info"
                  style={styles.input}
                  id="id"
                  onChangeText={(text) => setPassword(text)}
                  type="text"
                  placeholder="password"
                  value={password}
                  secureTextEntry/>
              </View>
              <View style={styles.btnContainer}>
                
             
               <TouchableOpacity style={styles.userBtn}>
                  <Text style={styles.userText} 
                  onPress={() =>
                    handleSubmit()}>Login</Text>
                  </TouchableOpacity>

                <TouchableOpacity  
                style={styles.userBtn}
                onPress={()=> alert('login works!')}>
                  <Text style={styles.userText}>Sign Up</Text>
                  </TouchableOpacity>
                 
              </View>
              {isLoggedIn ? (
                <Text>You are Logged IN!</Text>
              ) : (
                <Text>Come inside!</Text>
              )}
            
        </View>
      </ScrollView>
      </SafeAreaView>
    
  );
  }


Solution 1:[1]

In your handleSubmit function, after fetching the response store the data in AsyncStorage like this-

AsyncStorage.setItem("loginData", JSON.stringify(data));

Then fetch the data from Async storage in some async function (that you can call in useEffect).

let data = await AsyncStorage.getItem("loginData");

Solution 2:[2]

const LoginForm = ({navigation}) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [isLoggedIn, setIsLoggedIn] = useState(false);

async function handleSubmit(email, password) {
  const data = {email, password};
  console.log(data, 'this is dataa');

  const requestOptions = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',

      ACCEPT: 'application/json',
    },
    body: JSON.stringify(data),
  };

  fetch('API_HERE/auth/sign_in', requestOptions).then(async response => {
    //replace it with respect to your API token
    if (response.token) {
      await AsyncStorage.setItem('userToken', response.token); 
      setIsLoggedIn(true);
      if (setIsLoggedIn) {
        navigation.navigate('ProfileLanding');
      }
    }
  });
}

return (
  <SafeAreaView style={styles.container}>
    <ScrollView>
      <View style={styles.loginBar}>
        <Text style={styles.loginTitle}>Login to my app</Text>
        <View className="login-form">
          <TextInput
            className="login-info"
            style={styles.input}
            id="id"
            onChangeText={text => setEmail(text)}
            type="text"
            placeholder="[email protected]"
            value={email}
          />
          <TextInput
            className="login-info"
            style={styles.input}
            id="id"
            onChangeText={text => setPassword(text)}
            type="text"
            placeholder="password"
            value={password}
            secureTextEntry
          />
        </View>
        <View style={styles.btnContainer}>
          <TouchableOpacity style={styles.userBtn}>
            <Text
              style={styles.userText}
              onPress={() => handleSubmit(email, password)}>
              Login
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.userBtn}
            onPress={() => alert('login works!')}>
            <Text style={styles.userText}>Sign Up</Text>
          </TouchableOpacity>
        </View>
        {isLoggedIn ? (
          <Text>You are Logged IN!</Text>
        ) : (
          <Text>Come inside!</Text>
        )}
      </View>
    </ScrollView>
  </SafeAreaView>
);

};

Solution 3:[3]

Assume that you need to save the authentication token after successful login attempt.

function saveUserToken(token) {
  try {
    await AsyncStorage.setItem("userToken", token.toString());
  } catch (error) {
    // Error saving data
  }
}

async function handleSubmit() {
  const headers = await getUserToken(); //'profile'
  //console.log(headers, 'getusertoken')
  const data = { email, password };
  console.log(data, "this is dataa");

  const requestOptions = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",

      ACCEPT: "application/json",
    },
    body: JSON.stringify(data),
  };

  fetch("API_HERE/auth/sign_in", requestOptions).then(
    (response) => {
      //Mocked userToken access - replace with API data structure
      const userToken = response.data.userToken;
      // Save token on user device
      saveUserToken(userToken);
    }
  );

  //.then(res => console.log(res));
  //setEmail(true)
  //setPassword(true)
  setIsLoggedIn(true);
  if (setIsLoggedIn) {
    return navigation.navigate("ProfileLanding");
  }
}




Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 this.arjun
Solution 2 Ahsan Shakeel
Solution 3