Axios Post React Native Return Undefined Sometimes - react-native

Why my axios post return undefined sometimes ?
Check this code :
export const ApiConfigAxios = axios.create({
// * Begin =========================== Configuration API
baseURL: 'https://website.id/index.php',
withCredentials: true,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": `Basic ${base64data}`,
},
// * End =========================== Configuration API
});
export const ApiRegisterOrLoginUser = async (email, name, picture, givenname, familyname) => {
try {
// * Begin =========================== API
const response = await ApiConfigAxios.post('/AuthenticationAPI', {
email: email,
name: name,
picture: picture,
givenname: givenname,
familyname: familyname,
});
// * End =========================== API
if (response.data.Data.length === 2) {
let results = Object.assign(response.data.Data[0], response.data.Data[1]);
return results;
} else {
return response.data;
}
} catch (err) {
console.error(err);
}
};
The Problem Is :
When I clear data app from android setting and open the app then quickly click the sign in button I will got undefined
But when I clear data app from android setting and open the app then wait at least 3 second before click the sign in button it is working
what is the problem with the axios ?

Found the problem.
The problem is in server side. I have a post value (TOKENS) that cannot be null.
That is a Notification Tokens. It is inside useEffect.
So in my app I check if TOKENS != null (delay until the token generate) then the button login show.
Also to make a better user experience when got undefined I check in my API Axios :
if (typeof response == 'undefined') {
return "FAILED";
}
When user login and receive undefined I will prompt a Message Box rather than loading without end. So user can try login again.

Related

How to get data correctly using the Spotify API with React

I have the following problem when I request data from the Spotify API, at first I get it, but when I reload the page or try to write this state using useState, an error 400 or 401 occurs. The code I use to get the data:
`
import axios from 'axios';
const BASE_URL = 'https://api.spotify.com/v1';
export const fetchFromAPI = async (url: string, token: string) => {
const { data } = await axios.get((`${BASE_URL}/${url}`), {
method: 'GET',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
});
return data;
}
`
Next, I use the fetchFromAPI function:
`
const { token } = useContext(Context);
const [albums, setAlbums] = useState<string[]>([]);
useEffect(() => {
fetchFromAPI('browse/new-releases', token)
.then((data) => console.log(data));
}, [token])
`
I've tried logging out of my account and back in, I've also tried other links to get data but it's always the same problem. I also checked if the token is present before requesting the data and it is
Ok, I managed to find and solve this error myself.
The error was that I didn't have a user token yet, but useEffect was already starting to receive data.
useEffect(() => {
if (token) {
fetchNewReleases();
fetchFeaturedPlaylists();
fetchCategories();
fetchRecommendations();
} else {
console.log('error');
}}, [token])
For example, this piece of code will print an error twice, and only after that I receive a token and can receive data from the API.
To be honest, I didn't know how to run useEffect only when I have a token, so I solved it in a simpler way, but I don't know if it's completely correct, I have the following condition Object.values(state).length) !== 0 and if it is true, only then will I display the data from the API

Not Getting anything back after calling Fetch API - React Native

I am creating a React Native in which i am sending my Form's data to Backend Node.js using Fetch and that worked all fine but i cannot execute anything down after fetch api, even console.log is not running.
React-Native Code:
const PostData = () =>{
console.log("Posting");
//Sending Request to Node.js using Fetch API
fetch("http://192.168.0.107:3000/Adminsignup", {
//Setting Method
method:"POST",
//Setting Headers
headers:{
//Setting Content-Type
"Content-Type" : "application/json"
},
//Stringifying the email and password and storing it into body
body:JSON.stringify({
name,
gmail,
password,
retype
})
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
}
.then and .catch of fetch api is not working.
Ok so your front-end code is all good and as u said that your backend is also working when you fire PostData() function, check if you are returning the response from backend.
Add this in your signup Route:
res.status(200).send({result:"Successfully got Response"})
Catch status in your front-end like this:
let final = await fetch("http://192.168.0.107:5000/studentSignup", {
//Setting Method
method:"POST",
//Setting Headers
headers:{
//Setting Content-Type
"Content-Type" : "application/json"
},
//Stringifying the email and password and storing it into body
body:JSON.stringify({name,gmail,password,retype})
})
const data = final.status;
if(data === 200)
{
navigation.navigate("Your Route");
}

Lose user data in Nuxt-auth fetchUser CustomStrategy

Hi everyone!
I have my own custom strategy to get token, and all is good, but when a refresh page I lose user data and fetchUser does not works. It doesn´t send the params to API to get again the user data.
the workflow is next:
1- send params to token api and get token
2- send params to login API to get the user
//nuxt.config.js
customStrategy: {
_scheme: '~/schemes/customScheme',
endpoints: {
login: {
url: '/api/v1/token',
method: 'post',
propertyName: 'token',
headers: {'x-channel-id': 1}
},
user: {
url: '/api/v1/login',
method: 'post',
propertyName: false,
headers: {'x-channel-id': 1}
},
logout: null
}
}
customScheme.js
import LocalScheme from '#nuxtjs/auth/lib/schemes/local'
export default class CustomScheme extends LocalScheme {
_setToken (token) {
if (this.options.globalToken) {
// Set Authorization token for all axios requests
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, token)
}
}
_clearToken () {
if (this.options.globalToken) {
// Clear Authorization token for all axios requests
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, false)
}
}
mounted () {
if (this.options.tokenRequired) {
const token = this.$auth.syncToken(this.name)
this._setToken(token)
}
return this.$auth.fetchUserOnce()
}
async login (endpoint) {
if (!this.options.endpoints.login) {
return
}
// Get token
const result = await this.$auth.request({
...endpoint
},
this.options.endpoints.login
)
// Set token
if (this.options.tokenRequired) {
const token = this.options.tokenType
? this.options.tokenType + ' ' + result
: result
this.$auth.setToken(this.name, token)
this._setToken(token)
}
// If result I get and set user
if (result) {
const user = await this.$auth.request({
...endpoint
},
this.options.endpoints.user
)
this.$auth.setUser(user);
}
}
async fetchUser (endpoint) {
// User endpoint is disabled.
if (!this.options.endpoints.user) {
this.$auth.setUser({})
return
}
// Token is required but not available
if (this.options.tokenRequired && !this.$auth.getToken(this.name)) {
return
}
// Try to fetch user and then set
try{
const user = await this.$auth.requestWith(
this.name,
endpoint,
this.options.endpoints.login
)
this.$auth.setUser(user)
} catch (error){
console.log(error)
}
}
}
When I set this.$auth.setUser(user) in login() method all is fine and app redirect me to /dashboard page and the user information (like role and email) is displayed on navBar but when I refresh page I lose user data. The app try to fetchUser but it give me a 400 error because user and password not sent.
Another thing I don´t understand is Why endpoint parameter is undefined in async fetchUser (endpoint) ??? . I think there is an issue in this part.
I hope u can help me
Regards
I just remove all this library and did my own custom Nuxt authentication
https://nemanjadragun92.medium.com/nuxt-js-custom-authentication-245d2816c2f3

axios.post is returning error when used with redux-saga

I recently converted my redux-thunk middleware code to use redux-saga and it was working all these days fine and all of a sudden it is throwing an error. Not sure why!!
My Spring Boot REST Client is returning the proper response and no errors in the log. And if i make the same request using swagger i am getting the response back as expected so there is nothing wrong on the server side.
I have the following code
const LOGIN_URL = 'http://localhost:8888/api/a/login';
export function* loginUserAsync(action) {
console.log('.loginUserAsync() : action:', action);
yield put({ type: LoginConstants.LOGIN_USER_IN_PROGRESS });
const postParams = {
username: action.props.username,
password: action.props.password
};
const headerParams = {
headers: {
'Content-Type': 'application/json',
//'Content-Type': 'x-www-form-urlencoded'
}
};
console.log('headerParams', headerParams);
console.log('postParams', postParams);
try {
console.log('Before making async post call using axios');
const response = yield call(axios.post, LOGIN_URL, postParams, headerParams);
let token;
console.log('response', response);
if (response.headers) {
token = response.headers['x-auth-token'];
AsyncStorage.setItem('jwt', token);
}
// Login Succeeded fire Login Success Action
yield put({
type: LoginConstants.LOGIN_USER_SUCCESS,
token,
account: response.data
});
const navigatorUID = Store.getState().navigation.currentNavigatorUID;
Store.dispatch(NavigationActions.push(navigatorUID, Router.getRoute('home')));
} catch (error) {
// Login Failed fire Login Failure Action
console.log('loginUserAync() : error:[' + JSON.stringify(error) + ']');
yield put({
type: LoginConstants.LOGIN_USER_FAILURE,
error: error.data
});
}
}
export function* loginUser() {
console.log('.loginUser() :');
yield takeEvery(LoginConstants.LOGIN_USER, loginUserAsync);
}
In the console i am seeing the following:
I have no idea why it stopped working all of a sudden.
Thanks
Sateesh
For some reason localhost and 127.0.0.1 are not being recognized and i have to use the actual IP Address.
I had that Issue when i tried to run it in my mac book. It always worked with localhost in Ubuntu.

Fetching userinfo from Auth0 application in React Native

I'm using Auth0's react-native-lock widget for user authentication, and after a successful login I'm storing the tokens with AsyncStorage.
If a user comes back to the app, I'd like to be able to skip the login and simply fetch the current userinfo from Auth0. It seems incredibly easy from the the Auth0 API docs but I'm getting back the message "Unauthorized" in my app:
async getUserinfo() {
console.log('getting user info in getUserInfo()');
try {
let response = await fetch('https://xxxxx.auth0.com/userinfo', {
method: 'GET',
headers: {
Authorization: 'Bearer ${this.state.token.accessToken}',
},
});
let responseJson = await response.json();
if(responseJson !== null) {
console.log('Got user info: ' + responseJson.email);
this.setState({ component: Temp, isLoading: false, profile: responseJson});
}
} catch (error) {
console.log('Error in retrieving userinfo from Auth0: ' + error.message);
this.setState({ component: Login, isLoading: false});
}
}
What am I missing? I can't find many examples of using fetch with Auth0, is there a better method I should be using?
Problem identified in the scope of an associated GitHub issue. In case anyone lands here and not where the issue got solved, the problem is that you need to use:
Authorization: 'Bearer ' + this.state.token.accessToken,
Original code tried to access the variable within a string literal 'Bearer ${this.state.token.accessToken}'.