React Native async await dispatch store - react-native

So I want to make a login feature, in here server will validate first if the username or password is correct or not.
I'm using store, react - redux.
Here is my code when login button pressed
const [statusLogin,setStatusLogin] = useState(null)
let loginInfo = []
function loginButton(){
(async () => {
loginInfo = {username:username,password:password}
const { status } = await dispatch(getUser(loginInfo))
if (status==1){
console.log(status,'in status if 1')
setStatusLogin('granted')
}else{
console.log(status,'in status if else')
setStatusLogin(null)
}
})();
}
Here is my store that suppose to return value 1 or else
if it returned value 1 geb statusLogin will changed as granted
export function getUser(body){
return dispatch =>{
if (!body){
setTimeout(() => {
console.log('no username/pass')
}, 2000);
}else{
setTimeout(() => {
console.log('username/pass validated returning with value 1')
}, 2000);
}
}
}
help me please

This might help
...
function loginButton() {
(async () => {
loginInfo = { username: username, password: password };
await dispatch(getUser(loginInfo, callback));
})();
}
function callback = (status) => {
if (status == 1) {
console.log(status, "in status if 1");
setStatusLogin("granted");
} else {
console.log(status, "in status if else");
setStatusLogin(null);
}
};
reducer.js
export function getUser(body, callback){
return dispatch =>{
if (!body){
setTimeout(() => {
console.log('no username/pass');
callback(0);
}, 2000);
}else{
setTimeout(() => {
console.log('username/pass validated returning with value 1')
callback(1);
}, 2000);
}
}
}

you can use like:
usEffect(( )=>{
if(statusLogin) getUser()
},[statusLogin])
Another thing, your function should not passed callback in. Instead of using callback to change the state, you can use dispatch to modify the reducer.

Related

React Redux rejectWithValue() not working

I'm currently facing a problem, when I try to reject a value when my node-fetch request fail, thunkApi.rejectWithValue() isn't working. However when my request is pending or when It's fulfilled, It's working fine.
Here's my slice :
export const userSlice = createSlice({
name: "user",
initialState: initialState as User,
reducers: {
...
},
extraReducers: (builder) => {
...
builder.addCase(changePassUser.pending, (state) => {
GGLog("FETCHING CHANGEPASS API...");
state.isFetching = true;
return state;
});
builder.addCase(changePassUser.fulfilled, (state, { payload }) => {
GGLog("FULFILLED CHANGEPASS:", JSON.stringify(payload));
state.isFetching = false;
state.isSuccess = true;
state.isError = false;
return state;
});
// eslint-disable-next-line #typescript-eslint/no-explicit-any
builder.addCase(changePassUser.rejected, (state, { payload }: any) => {
GGLog("REJECTED CHANGEPASS:", JSON.parse(payload));
state.isFetching = false;
state.isError = true;
state.errorMessage = payload.data;
return state;
});
},
});
Here's my thunk :
export const changePassUser = createAsyncThunk(
"users/password/update",
async ({ oldpassword, newpassword }: RegisterParameters, thunkAPI) => {
try {
const res = await changePassApi.changePass.return({
oldpassword: oldpassword,
newpassword: newpassword,
});
GGLog("API_CHANGEPASS_RES:", res);
const data = await res.json();
if (res.ok) {
GGLog("API_DATA_RESPONSE_OK: ", data);
const tokenData = JSON.stringify(res.headers);
const token = JSON.parse(tokenData).map["x-auth"];
await localStorage.store("token", token);
return data;
} else {
GGLog("API_DATA_RESPONSE_NOK: ", data);
return thunkAPI.rejectWithValue(data);
}
} catch (e) {
GGLog("Error while fetching Login API => ", e);
return thunkAPI.rejectWithValue(e);
}
}
);
And here's the result in the console :
Console output
Any ideas ? Am I missing something ?
Thanks :)
Okay I've found my problem, I was just focused on the thunk and didn't pay attention to the promise rejection. I was trying to parse a JSON that does'nt exist... Just remove the GGLog("REJECTED CHANGEPASS:", JSON.parse(payload));in the slice.
It's working fine now !

React Native UseEffect function is not working according to order

I want to get user's current location and set it into AsyncStorage a array. I will do it in the useEffect hook. But the problem is my functions are not working that according to given order. Here are my code
useEffect(() => {
getUserLocation();
setUserLocation();
check();
}, []);
/*Get User's Currunt Location*/
const getUserLocation = () => {
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000,
})
.then((location) => {
var lt = location.latitude;
var lg = location.longitude;
setlatitude(lt);
setlongitude(lg);
console.log("getUserLocation", lt, lg);
})
.catch((error) => {
const { code, message } = error;
console.warn(code, message);
});
};
/*Set User's Currunt Location to AsyncStorage*/
const setUserLocation = async () => {
try {
await AsyncStorage.setItem("user_location", JSON.stringify(userLocation));
console.log("setUserLocation", userLocation);
} catch (error) {
console.log("error setting user location");
}
};
const check = () => {
AsyncStorage.getItem("user_location", (err, result) => {
if (result !== null) {
console.log("check", result);
setlatitude(result.latitude);
setlongitude(result.longitude);
} else {
console.log("Data Not Found");
}
});
};
Whenever you use .then you are scheduling your code to run at some point in the future, when the promise has completed. So setUserLocation runs before the then of getUserLocation.
Also, it looks like your getUserLocation set react state, which won't be available until the next render. We use effects to manage this.
// Get the location on mount
useEffect(getUserLocation, []);
// Whenever the location updates, set it into storage
useEffect(() => setUserLocation().then(check), [latitude, longitude]);

Using AsyncStorage to show screen on first login

I'm trying to only show the disclosure screen the first time the user logs in by using AsyncStorage. Currently getData is returning a Promise and it goes straight to the landing screen on first login.
Could I get some help to get this functioning the way I want it to?
This is my login handler:
const key = 'key';
const storeData = async () => {
try {
await AsyncStorage.setItem('key', 'true');
} catch (error) {
// saving failed
console.log(error.message);
}
};
const getData = async key => {
let value = '';
try {
value = await AsyncStorage.getItem(key);
return JSON.parse(value);
} catch (e) {
console.log(error.message);
}
};
const _loginHandler = () => {
if (userName == '' || password == '') {
console.log('gagagagagagagagagagagagagagagagag');
} else {
setShowLoading(true);
const payload = {userName: userName.trim(), password: password.trim()};
setUserName('');
setPassword('');
_UserLoginHandler(payload).then(data => {
setShowLoading(false);
if (data.error) {
GlobalShowSnackBar(data.error);
} else {
setTimeout(() => {
setUserId(data);
//props.navigation.replace(getData("key")?'Landing':'Disclosure')
console.log('Key Value ' + JSON.stringify(getData('key'))); <-- this outputs Key Value {"_U":0,"_V":0,"_W":null,"_X":null}
if (getData('key')) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
}, 500);
}
});
}
};
I got it to work with
getData('key').then(val => {
if (val) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
});

How to execute code after action finished in vue js?

How to execute code after action finished in vue js? this is my login action
login: async ({commit},loginDTO)=>{
return commit('login',loginDTO);
}
My login mutations is this:
login:(state, loginDTO)=>{
axios.post(loginEndpoint.login, loginDTO)
.then(resp => {
if(resp.data.statusCode == 1) {
state.user.userId = resp.data.userId;
state.user.response = resp.data.responseText;
localStorage.setItem("token", "token")
state.isLogin = true;
router.push({name: 'Systems'});
}
else{
alert(66);
state.user.response = resp.data.responseText;
}
})
.catch(err => {
})
}
And I call it from component like this:
methods:{
...mapActions(['login']),
async login1(){
const loginDTO = {
Username : this.user.Username,
Password: this.user.Password
};
await this.$store.dispatch('login',loginDTO);
this.$toastr.s("Message", "");
}
}
Now I need toast message but after action is completed.
Updated.
Make use of async-await, and await for async action to complete and sync mutation to commit before you show the toast:
// action
login: async ({commit},loginDTO)=>{
try {
const { data } = await axios.post(loginEndpoint.login, loginDTO)
commit('login', data.userId, data.responseText, true);
} catch(error) {
commit('login', null, error.message, false);
}
}
// mutation
login: (state, userId, response, isLogin) {
state.user.userId = userId;
state.user.response = response;
state.isLogin = isLogin
}
methods:{
...mapActions(['login']),
async login1(){
const loginDTO = {
Username : this.user.Username,
Password: this.user.Password
};
await this.$store.dispatch('login',loginDTO);
this.$toastr.s("Message", "");
}
}
I think all you need to do is call the toast function after the action complete as usual, callback function after ajax returns 200, for example, I used
https://github.com/ankurk91/vue-toast-notification
then run it like so on the callback
this.$toast.open('You did it!');
(make sure the toast has been registered on your vue instance)

Catch Axios exception in Vuex store and throw it to Vue.js method

How to catch axios exceptions in vuex store and throw it to vue.js method ? My goal is to get this exception to be able to reset computed values bound to input using this.$forceUpdate().
In my method, I have this:
methods: {
mymet: _.debounce(
function(table, id, key, event) {
const value = event.target.value;
this.$store.dispatch('UPDATE_TRANSACTIONS_ITEM', { table, id, key, value }).then(response => {
event.target.classList.remove("is-invalid")
event.target.classList.add("is-valid")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
this.$forceUpdate();
})
}, 500
)
}
In my vuex store, I have this:
const actions = {
UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
let company = {
[data.key]: data.value
}
axios.put(`/api/companies/${data.id}`, { company }).then( function ( response ) {
commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data })
}).catch(function (error) {
throw error
})
}
}
const mutations = {
SET_TRANSACTIONS_ITEM_UPDATE (state, { profile }) {
state.company_data[profile.key] = profile.value
},
}
You need to make the actual action function asynchronous.
If you have the ability to use async functions, you can just await the axios call, and let the error bubble up (no need to throw anything in the action itself):
const actions = {
async UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
let company = {[data.key]: data.value};
await axios.put(`/api/companies/${data.id}`, { company }).then(() => {
commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data })
});
}
}
Otherwise, you'll need to return a Promise and catch the error and pass it to the reject handler:
const actions = {
UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
return new Promise((resolve, reject) => {
let company = {[data.key]: data.value};
axios.put(`/api/companies/${data.id}`, { company }).then(() => {
commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data });
resolve();
}, (error) => reject(error));
});
}
}