Home > database >  React native WARN Possible Unhandled Promise Rejection (id: 2): Error: [AsyncStorage] Passing null/u
React native WARN Possible Unhandled Promise Rejection (id: 2): Error: [AsyncStorage] Passing null/u

Time:02-23

In react native cli i was trying to login but not working nd same thing working fine in expo nd this error is showing please let me know what can i do to do this???? i have added the action ,reducer,component page

getting error this //

WARN Possible Unhandled Promise Rejection (id: 2): Error: [AsyncStorage] Passing null/undefined as value is not supported. If you want to remove value, Use .removeItem method instead. Passed value: undefined Passed key: userToken checkValidInput@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.easylab&modulesOnly=false&runModule=true:146791:24 http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.easylab&modulesOnly=false&runModule=true:146835:24..........................

my action is like this // actions>index.js page

export const login = (formValues, actions) => {
return async dispatch => {
dispatch(startSubmitting());
const url = `/auth/login`;
var formdata = new FormData();
formdata.append('email', formValues.email);
formdata.append('password', formValues.password);
const response = await api
  .post(url, formdata)
  .then(res => {
    return res;
  })
  .catch(error => {
    actions.setErrors(error.response.data.error);
    return error.response;
  });
dispatch({
  type: 'LOGIN',
  payload: response,
});
dispatch(stopSubmitting());
await AsyncStorage.setItem('userToken', response.data.access_token);

}; };

//my component page login.js

import { StatusBar } from "expo-status-bar";
import React, { useState, useEffect } from "react";
import {
Field,
Form,
Formik,
FormikProps,
ErrorMessage,
useFormik,
} from "formik";
import { connect } from "react-redux";
import { login } from "../../../actions";
import { Button } from "react-native-paper";
import ErrorMsg from "./ErrorMsg";


class Login extends React.Component {

submitLogin = (values, actions) => {
this.props.login(values, actions);
 
};


render() {
const { onChangeText, text, navigation } = this.props;
const { isSubmitting ,isLoading} = this.props.commonData;
const { login, loginLoading, isLoggedIn } = this.props.loginForm;
{
  login && this.props.navigation.navigate("Nav1");
}
return (
  <KeyboardAvoidingView
    behavior={Platform.OS === "ios" ? "padding" : "height"}
    style={styles.container}
  >
    {/* {verifyOtp ? <Loader loading={verifyOtp} /> : null} */}
   
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <View style={styles.inner}>
        <View style={{ alignItems: "center" }}>
          <Image
            source={require("../../../assets/images/diabetes-awareness-month-1440x810.jpg")}
            style={{
              height: 110,
              //   top: -20,
              resizeMode: "contain",
            }}
          />
        </View>
        <View style={{}}>
          <Text onPress={() => this.props.navigation.navigate("Register")}>
            New User ? Register
          </Text>
        </View>
        <View style={{}}>
          <Text style={{ fontSize: 24, fontWeight: "bold" }}>LOGIN</Text>
        </View>
        <View style={{}}>
          

          <Formik
            initialValues={{
              email: "",
              password: "",
            }}
            validate={(values) => {
              const error = {};
              if (!values.password) {
                error.password = (
                  <Text style={{ color: "red", fontSize: 10 }}>
                    Password Required
                  </Text>
                );
              }
              if (!values.email) {
                error.email = (
                  <Text style={{ color: "red", fontSize: 10 }}>
                    Email Type Required
                  </Text>
                );
              }

              return error;
            }}
            onSubmit={(values, actions) => {
              this.submitLogin(values, actions);
            }}
            enableReinitialize={true}
          >
            {(props: FormikProps<any>) => (
              <>
                <View style={{ paddingBottom: 10 }}>
                  <Text>Login To Check Your Account</Text>
                </View>

                <View>
                  {/* email  */}
                  <View style={{ marginBottom: 20 }}>
                    <View style={styles.textInputContainer}>
                      <MaterialCommunityIcons
                        style={{ alignSelf: "center", paddingLeft: 10 }}
                        name="email"
                        size={28}
                      />
                      <TextInput
                        style={styles.input}
                        onChangeText={props.handleChange("email")}
                        value={props.values.email}
                        autoFocus={true}
                        placeholder="Email"
                      />
                    </View>
                  </View>
                  
                  <View style={{ marginBottom: 20 }}>
                    <View style={styles.textInputContainer}>
                      <MaterialCommunityIcons
                        style={{ alignSelf: "center", paddingLeft: 10 }}
                        name="security"
                        size={28}
                      />
                      <TextInput
                        style={styles.input}
                        onChangeText={props.handleChange("password")}
                        maxLength={10}
                        secureTextEntry={true}
                        value={props.values.password}
                        placeholder="Password"
                      />
                    </View>
                  </View>
                  {/* {props.touched.password && props.errors.password && ( */}
                  <ErrorMsg msg={props.errors.password} />
                  {/* )} */}
                  <TouchableHighlight
                    underlayColor="white"
                    onPress={props.handleSubmit}
                  >
                    <Text color="white" style={styles.buttonStyle}>
                      {/* {isSubmitting ? (
                            <ActivityIndicator
                              size="small"
                              color="#4DB2F8"
                            />
                          ) : ( */}
                      <Text>LOGIN </Text>
                      {/* )} */}
                    </Text>
                  </TouchableHighlight>
                </View>
              </>
            )}
          </Formik>
        </View>
      </View>
    </TouchableWithoutFeedback>
  </KeyboardAvoidingView>
);
}
}
const mapStateToProps = (state) => {
return {
loginForm: state.loginData,
commonData: state.commonFunctions,

};
};
 export default connect(mapStateToProps, { login })(Login);

and in redux trying to store like this// reducers>index.js page

const loginReducer = (
state = {
otp: false,
mobile: null,

login: false,
loginLoading: true,
verifyOtp: false,
isLoggedIn: false,
 },
 action
 ) => {
 switch (action.type) {
 case "LOGIN": {
  if (action.payload.status === 200) {
    let newState = { ...state, login: true, isLoggedIn: true };
    return newState;
  } else {
    let newState = { ...state, login: false, isLoggedIn: false };
    return newState;
  }
  }
   default:
  return state;
}
 };
 export default combineReducers({

 loginData: loginReducer,

 });

CodePudding user response:

Your problem is that you are trying to set userToken to null on this line:

await AsyncStorage.setItem('userToken', response.data.access_token);

You need to do a null check before setting the token, since Async Storage does not support setting null values. Try:

if (response && response.data && response.data.access_token) {
    await AsyncStorage.setItem('userToken', response.data.access_token);
}
  • Related