jwt-decode warning in react-native - react-native

in react-native (implementing Jafar´s answer) I am checking the token-validity like this:
// navigation
const navigation = useNavigation()
// config request: check token expiry-validity
const checkTokenValidity = async (next) => {
const token = state && state.token ? state.token : ''
let err
const decodedToken = jwt_decode(token)
console.log('Decoded Token-----> ', decodedToken)
let currentDate = new Date()
if (decodedToken.exp * 1000 < currentDate.getTime()) {
err.message = 'Token has expired.'
await AsyncStorage.removeItem('auth-rn')
setState({ user: {}, token: '' })
next(err)
} else {
console.log('Valid token')
}
}
// run checkTokenValidity
checkTokenValidity((err) => {
if (err) {
console.log(`Token error: ${err.message}`)
alert(
'Your session is older than 7 days and it has expired. You´ll be redirected to log-in now.'
)
navigation.navigate('SignIn')
}
return
})
It actually works all fine, but it throws this WARN in the console:
WARN Possible Unhandled Promise Rejection (id: 0):
[InvalidTokenError: Invalid token specified: undefined is not an object (evaluating 'e.replace')]
I tried some Promise Rejection options as "try and catch" and callbacks, but the warning persists.
I would appreciate if someone has an idea what is the code exactly asking for. Thx!

Related

axios interceptor blocking api calls in redux saga

I have a react native project in which I'm calling some API's using redux-saga mechanism. Now when I added response interceptor for axios my saga api's are not working anymore. Does any knows how I can fix this?
here is the code for my axios instance class and response interceptor
const getLoggedInUser = async () => {
const savedUser = JSON.parse(
await getDataFromAsyncStorage(APP_CONSTANTS.SAVED_USER)
)
if (savedUser?.user_id != null) {
return savedUser
}
return null
}
const baseapi = axios.create({
baseURL: APP_CONSTANTS.BASE_URL,
headers: {},
})
baseapi.interceptors.request.use(
async (config) => {
const token = await getLoggedInUser()
const userId = token?.user_id
const authToken = token?.token
if (token) {
baseapi.defaults.headers.common['userId'] = token
baseapi.defaults.headers.common['token'] = authToken
}
return config
},
(error) => {
return Promise.reject(error)
}
)
// Response interceptor for API calls
baseapi.interceptors.response.use(
(response) => {
return response
},
async function (error) {
const originalRequest = error.config
if (error.response.status === 403 /* && !originalRequest._retry */) {
return baseapi(originalRequest)
}
return Promise.reject(error)
}
)
This is my saga class code and it fails directly when I add a response interceptor
function* getTopicList(action) {
try {
yield put({type: ACTION_TYPES.START_TOPIC_LIST})
const {payload} = action
const res = yield call(getAllTopicsOfBatch, payload)
if (res?.status == APP_CONSTANTS.SUCCESS_STATUS) {
yield put({
type: ACTION_TYPES.SET_TOPIC_LIST,
payload: {data: res?.data?.topics},
})
} else {
alert('OOPS Something went wrong! Please try again')
yield put({
type: ACTION_TYPES.ERROR_TOPIC_LIST,
payload: 'Something Went Wrong Please Try Again',
})
}
} catch (error) {
console.log('RESPONES error', error)
alert('OOPS Something went wrong! Please try again')
yield put({
type: ACTION_TYPES.ERROR_TOPIC_LIST,
payload: 'Something Went Wrong Please Try Again',
})
}
}
The code looks mostly fine, the only two things I found that are likely causing problems are:
In the request interceptors you are likely wrongly passing the whole token as userId instead of userId
baseapi.defaults.headers.common['userId'] = token // 'token' should be 'userId'
In the response interceptors error handler, you are not guaranteed to have 'response' property on error.
if (error.response.status === 403) // use error?.response
If neither of these things will fix your problem my guess is you have a problem in your endpoint and so you should examine the response errors you get to guide you.

Error: An error occurred while trying to log in to Facebook expo-facebook android issue

I am trying to implement Facebook login in a simple expo app but on the android expo client, it is not working. Following version, I am using.
"expo-facebook": "~12.0.3",
Method code
const handleAuth = async () => {
try {
let options = null;
if (Platform.OS === "android") {
options = {appId: "xxxxxxxxxxxxxx"};
} else {
options = {
appId: "xxxxxxxxxxxxxx",
version: "v9.0",
appName: "xxxxxxxx",
};
}
let res = await Facebook.initializeAsync(options);
console.log("[init res]", res);
const {type, token, expirationDate, permissions, declinedPermissions} =
await Facebook.logInWithReadPermissionsAsync({
permissions: ["public_profile"],
});
console.log("[type]", type);
console.log("[token]", token);
if (type === "success") {
// SENDING THE TOKEN TO FIREBASE TO HANDLE AUTH
const credential = app.auth.FacebookAuthProvider.credential(token);
app
.auth()
.signInWithCredential(credential)
.then((user) => {
// All the details about user are in here returned from firebase
console.log("Logged in successfully", user);
dispatch(saveUser(user));
navigation.replace("App");
})
.catch((error) => {
console.log("Error occurred ", error);
});
} else {
// type === 'cancel'
}
} catch (res) {
console.log("[res]", res);
// alert(`Facebook Login Error: ${res}`);
}
};
Another error i am facing is FacebookAuthProvider is not available in firebase
firebase": "8.10.0"
I have tried the following ways.
app.auth.FacebookAuthProvider
Or
app.auth().FacebookAuthProvider
but both are not working.
Please help if anyone integrated facbook login in. "expo": "~44.0.0"

Possible Unhandled Promise Rejection warning when axios call fails

Every time if there is a 504 or 404 from an API call that I make I get the warning:
Possible Unhandled Promise Rejection (id: 12):
ReferenceError: Can't find variable: rej
Here is how I've coded:
function myFunction() {
const fullURL = 'URL_THAT_I_HIT'
const data = { "SOME_ID": ID_VALUE, }
return new Promise((res, rej) => {
try {
axios.post(fullURL, data).then((response) => {
res(response.data)
}).catch((error) => {
rej(error)
alert(error)
})
} catch (error) {
rej(error)
alert(error)
}
})
}
As per my understanding, I'm handling the rej and I've even double wrapped it so that I can throw rejection. Here is my code below where I'm calling myFunction
function fetchMyFunctionCall() {
if (res === undefined) {
alert("The call rejected")
} else {
console.log(res)
}
}
It shows the error message but I still see the warning. So, how do I handle the rejection properly in fetchMyFunctionCall?
I wasn't able to repro your error for the undefined variable but I think you can simplify your code like below:
function myFunction() {
const fullURL = 'URL_THAT_I_HIT'
const data = {
"SOME_ID": ID_VALUE,
}
return axios.post(fullURL, data).then((response) => {
return response.data
});
}
myFunction().then((data) => {
console.log(data)
}).catch((error) => {
console.log(error)
})
Axios itself returns a promise so no need of returning one explicitly.

Prevent logging errors to console when using Axios interceptor

I've implemented axios interceptor in my VueJs project, which looks like this:
axios.interceptors.response.use(
async (response) => {
return response;
},
async (error) => {
const originalRequest = error.config;
const isPublicUrl = [
'/account/login',
'/account/register'
].some(url=> originalRequest.url.includes(url));
if(isPublicUrl){
return Promise.reject(error);
}
if(error.response.status!==401){
return Promise.reject(error);
}
const token:TokenOpts = store.getters['auth/getToken'];
try{
const res = await AuthService.refreshToken(token);
const newToken = res.data;
store.dispatch('auth/refreshToken',newToken);
originalRequest.headers.Authorization = `Bearer ${newToken.accessToken}`;
const originalResponce = await axios.request(originalRequest);
return Promise.resolve(originalResponce);
}
catch(error){
return Promise.reject(error);
}
}
)
I can refresh my token and then send original request, here no problems.
My problem is that when I intercept an error, and end up inside error handler: async (error) => { HERE ... I already have an error in Chrome console. How can I prevent logging this error into the console?
This has nothing to do with VueJs. All errors will be logged in the console as that is the default option enabled in your browser. Follow this link to disable your network error messages. Suppress Chrome 'Failed to load resource' messages in console

Tipsi-Stripe creating a source from a token

I am trying to use tipsi-stripe to create a source which I will send to my server. I get the token fine with following code but creating a source from the token
throws an error
try {
this.setState({ loading: true, token: null })
const token = await stripe.paymentRequestWithCardForm({
// Only iOS support this options
smsAutofillDisabled: true,
requiredBillingAddressFields: 'full',
prefilledInformation: {
billingAddress: billingAddress,
},
})
this.setState({ 'token': token })
var strToken=this.state.token;
console.log(strToken);
const params = {
type:'card',
token:strToken
}
const source = await stripe.createSourceWithParams(params)
Error is as follows
[Error: The payment method `card` requires the parameter: card[number].]
What am I doing wrong?