undefined is not an object this.props.auth from redux - react-native

I am trying to navigate to a different screen on success of my authentication function. This is the approach I'm taking, but I am getting undefined is not an object when I try to use .then()
This is my code
login = () => {
const {username, password} = this.state
this.props.authentication(username, password).then(res => {
})
}
const mapDispatchToProps = dispatch => {
return {
authentication: (username, password) =>
dispatch(authenticationLoginEmail(username, password)),
};
};
This my redux code
export const authenticationLoginEmail = (username, password) => {
return dispatch => {
dispatch(authLoginEmailStart())
axios.post('url',{username, password})
.then(res=>{
console.log(res.data.idusers,'ID USERS');
...
dispatch(authLoginEmailSuccess(idusers, token))
return res
})
.catch(err=>{
dispatch(authLoginEmailfail(err))
console.log(err);
})
}
}
Error
undefined is not an object (evaluating '_this.props.authentication(username, password).then')
thanks for helping

i think you should not use it like promise
this.props.authentication(username, password).then(res => { })
if you want to a response you have to just call this in your code
this.props.authentication(username, password);
And if your fetch finished you will send your success or error into redux state
dispatch(authLoginEmailSuccess(idusers, token))
or
dispatch(authLoginEmailfail(err))
and you can save your state in reducer and then get it into your component in mapStateToProps

Related

In reactnative expo I tried using secureStore from expo in redux to save token the one I get from api

I tried using redux to save token the one I get from api in react native ..its working now.
First one is for settoken and other one is for gettoken.
enter image description here
export const verifyOTP = (formValues, actions) => {
return async (dispatch) => {
dispatch(startSubmitting());
const url = `/validate-otp`;
var formdata = new FormData();
formdata.append("mobile", formValues.mobile);
formdata.append("otp", formValues.otp);
const response = await api.post(url, formdata);
dispatch({
type: "VERIFY_OTP",
payload: response,
});
dispatch(stopSubmitting());
await SecureStore.setItemAsync("userToken", response.data.access_token);
};
};
export const checkUser = () => {
return async (dispatch) => {
const token = await SecureStore.getItemAsync("userToken");
const url = `/me`;
const response = await api
.post(url, { token })
.then((res) => {
return res;
})
.catch((error) => {
return error.response;
});
dispatch({
type: "CHECK_USER",
payload: response,
});
};
};
The Problem
you are mixing two different implementations in checkUser to handle a promise which is clearly incorrect and leads to the issues.
The Solution
since your other parts of codes use the async/await so try to remove then/catch block from the response constant:
const checkUser = () => {
return async (dispatch) => {
const url = '/me';
try {
const token = await SecureStore.getItemAsycn("userToken);
const response = await api.post(url, {token})
dispatch({type: "CHECK_USER", payload: response})
} catch (error) {
// to proper action on failure case
}
}
}
Note 1: always use async/await in try/catch block. more on MDN documentation.
Optional
since you are trying to call two async actions (once for getting token and once for calling '/me' API), I encourage you to use two different try/catch blocks to handle the failure case for each async action separately. for example:
const checkUser = () => {
return async (dispatch) => {
let token = null;
try {
token = await SecureStore.getItemAsync("userToken");
} catch (err) {
// proper action in case of failure on getting the token from storage
}
// you may need to ignore API calls without the token, so:
try {
if(token){
const url = '/me';
const response = await api.post(url, {token});
dispatch({type: "CHECK_USER", payload: response});
}
} catch (err) {
// take proper action with the error response according to your applicaiton
}
}
}

Actions must be plain objects using Async Function for signout

Current code is not returning dispatch response
export const signOut = () => {
return async (dispatch) => {
try {
await AsyncStorage.removeItem("userToken");
dispatch({ type: "LOGOUT" });
} catch (e) {
console.log();
}
};
};
Main wallet Page for calling the action
Wallet
Returns nothing tried to add a callback response and I get nothing back...

sent a post request in actions and commit a data change with vuex

I am trying to set a boolean to true after submitting a new user with vuex but I get a strange error of Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
this is the create method in actions state
async CREATE_USER({state}) {
await axios.post('api/user', state.user)
commit('SET_CREATED_USER');
},
this is the mutation
SET_CREATED_USER: (state) => {
state.newUserCreated = true;
console.log('user create? -> ', state.newUserCreated);
}
and the on submit method
onSubmit() {
this.$store
.dispatch('CREATE_USER')
.then(() => {
this.inProgress = false;
// navigate to user
this.$router.push('users');
})
.catch( ({ response }) => {
this.inProgress = false;
this.errors = response.data.errors;
console.log('you have an error on creating an user')
});
},
I tried to add .then to the CREATE_USER method
axios.post('api/user', state.user).then(
() => commit('SET_CREATED_USER');
)
got the same error
I also tried
async CREATE_USER({state}, context) {
await axios.post('api/user', state.user)
context.commit('SET_CREATED_USER');
},
I also tried to remove the async and I get an error
Uncaught (in promise) ReferenceError: commit is not defined
Two issues:
You're trying to use commit in your action without access to it
async CREATE_USER({ state, commit }) {
await axios.post('api/user', state.user)
commit('SET_CREATED_USER');
},
You're trying to access response.data.errors but response is a nullable key so it's throwing an error. You can probably just use optional chaining to handle it.
.catch((error) => {
this.inProgress = false;
this.errors = error?.response?.data?.errors
console.log('you have an error on creating an user')
});

AsyncStorage not getting into then() method in react native

It seems like the async await doesn't work in react native. When I run the code below, it just logs 'here", not the value.
class CompanyDetails extends Component {
...
componentDidMount = async () => {
await this.getCompDetailsData();
}
getCompDetailsData = async () => {
console.log('here');
await AsyncStorage.getItem('CompanyID')
.then((value) => {
console.log(value);
const compID = JSON.parse(value);
console.log(compID);
this.props.getCompDetails(propID);
});
};
...
Does anyone know why it is happening?
Thanks
Did you had 'CompanyID' stored somewhere before because if you did not store it before then it will go to the catch part which is not implemented in your case
getCompDetailsData = async () => {
console.log('here');
await AsyncStorage.getItem('CompanyID')
.then((value) => {
console.log(value);
const compID = JSON.parse(value);
console.log(compID);
this.props.getCompDetails(propID);
}).catch(error => {
console.log("CompanyID is not defined yet");
});
};
You may not have a saved value in that name "CompanyID"

React Native - get data from Promise

in my React Native app I receive a token from an API. Everytime the app sends a request to the server this token is needed. I save the token in the AsyncStorage:
export const onSignIn = (value) => AsyncStorage.setItem('USER_TOKEN', value);
In many different parts of the app I need this token and therefore I wanted to use a function, that extracts the information out of the token:
export const getTokenInfo = async () => {
try{
const value = await AsyncStorage.getItem('USER_TOKEN')
.then((res) => {
const jsonData = jwtDecode(res);
return jsonData;
})
}
catch(e){
console.log('caught error', e);
}
}
When calling the function in other Components it just returns the Promise itself and not the token. Is there a possibility to get the token, but not the promise? A possible approach was to use setState() to store the token in a state, but there are some components like DrawerNavigator that are not in a class.
Thanks!
Your forgot to return the value on your getTokeninfo function
export const getTokenInfo = async () => {
try{
const value = await AsyncStorage.getItem('USER_TOKEN')
.then((res) => {
const jsonData = jwtDecode(res);
return jsonData;
})
return value // <---- you forgot this line
}
catch(e){
console.log('caught error', e);
}
}