I have a login function that is supposed to trigger an AXIOS POST request and get the response and save it in AsyncStorage (I am in React Native). Same code works on React however here I am not able to run it. To debug it, I placed several alert functions. The login function does not go further than the "second call"
I am not able to understand (now for days) why the rest of the function is not triggered, and if it is, no error is apparent.
Here is my function:
export const login = (email, password) => async(dispatch) => {
try {
dispatch({ type: USER_LOGIN_REQUEST });
alert('first call')
const config = {
headers: {
"Content-type": "application/json"
}
}
alert('second call')
const { data } = await axios.post("url/login", {email, password}, config)
alert('third call')
dispatch({type: USER_LOGIN_SUCCESS, payload:data});
alert('fourth call')
alert(JSON.stringify(data) `hello`)
await AsyncStorage.setItem("userInfo", JSON.stringify(data))
alert('final call')
alert(userInfo)
} catch (error) {
dispatch({
type: USER_LOGIN_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
})
alert("This login attempt is unsuccessful");
alert(error)
}
}
CodePudding user response:
If you could confirm that the axios request is indeed sent, then something must be wrong with your axios request (or the server receiving this request).
Did you check whether the request throws an error and you catch
block is executed? (For example because of some CORS issues)
If the catch
block is not executed then the promise returned by the axios request did not resolve/reject yet. The reason for this could be a server-side issue - is something keeping your server from responding? Are you calling the server with the correct URI?
In your code example you specify the path url/login
; this can work as a valid URI on the web (because axios appends this relative path to your current window.location.pathname
), however, mobile apps have no concept of a domain
the way web-apps have it. So the same request will fail in react native. Instead, specify the full path ({protocol}://{domain}/{path}
) of your server and see if that works.
CodePudding user response:
The way to solve this (at least for me) turned out to downgrade from React Native 0.66 to 0.64. I was always getting a warning with Expo app saying that Expo SDK would better work with 0.64.
When I had no other recourse to take, I downgraded to 0.64, did not change the code and the requests and the axios posts are being returned/executed now.
In case anyone encounters this kind of a problem, please take note of version errors that do not reveal themselves as I had been stuck at this for 4 days now.