I want to make a ping in my project. I have already tried the ping-litle library but it is not working. I also tried this :
var request = new xhtmlrequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success');
} else {
console.log('error');
}
};
request.open('GET', 'http://192.168.0.254/');
request.send();
But when I call the function a second time I have the same result even if my host is disconnected.
Have you an idea to make a good ping in React Native ?
or how to destroy my xhtmlrequest ?
Use the fetch API which is provided by react-native.
Your code would look like this:
fetch('http://192.168.0.254')
.then((response) => {
if (response.status === 200) {
console.log('success');
} else {
console.log('error');
}
})
.catch((error) => {
console.log('network error: ' + error);
})
Related
I dont know much of javaScript and i wanted to make a bot from a youtube tutorial. Now the video said to type this:
(async () => {
try {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
});
console.log("Globally");
} else {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID)
, {
body: commands
});
console.log("Locally");
}
}
} catch (err) {
if (err) console.error(err);
}
})
Inside the client.once("ready",
So it turned out something like this:
client.once("ready", () => {
console.log("Bot is online.");
const CLIENT_ID = client.user.id;
const rest = new REST({
version: "9"
}).setToken(process.env.TOKEN);
(async () => {
try {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
});
console.log("Globally");
} else {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID)
, {
body: commands
});
console.log("Locally");
}
}
} catch (err) {
if (err) console.error(err);
}
})
});
Now as you can see it says that if it finds client id it should type on console "Locally" to see if it works. But the terminal is like it ignores the whole async it just says that the bot is online nothing for the commands. What did i do wrong
Instead of defining a separate asynchronous function inside the ready handler function, why not just make the ready handler function itself asynchronous? Here's an example:
client.once("ready", async () => {
console.log("Bot is online.");
const CLIENT_ID = client.user.id;
const rest = new REST({
version: "9"
}).setToken(process.env.TOKEN);
try {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
});
console.log("Globally");
} else {
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID)
, {
body: commands
});
console.log("Locally");
}
} catch (err) {
if (err) console.error(err);
}
});
That should allow the async function to run.
EDIT
Your if statements were slightly incorrect. You are checking if process.env.ENV equals production, and else, you are once again checking if it equals production. I've fixed that in this answer.
This is my current code:
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
axios.get("/auth/token").then((res) => {
if (res.status === 200) {
console.log("Access token refreshed");
return axios(originalRequest);
}
});
} else {
return Promise.reject(error);
}
}
);
It's refreshing the token as expected, but it's not retrying the original request. If the request was to, let's say, display some data, I'm only able to see it if I reload the page or change to some other route and back again to re-render the component.
In my understanding, if the original request hits an error 401, then the interceptor should refresh the token and retry that call - which would trigger the interceptor again, but now would get a successful response - and pass this new response back to the original promise, right?
You need to return the axios function:
...
return axios.get("/auth/token").then((res) => {
if (res.status === 200) {
console.log("Access token refreshed");
return axios(originalRequest);
}
});
I'm new to react native currently i'm working on a project that needs to update a specific value in async storage. I tried by clearing an item from Asyncstorage using this code await AsyncStorage.removeItem(key); but when i used it console throws an error like this 'await' is only allowed within async functions . But i'm using an async function
const getExceedCountData = async () => {
const token = await AsyncStorage.getItem("#userToken")
const exceedcount = await AsyncStorage.getItem("#exceedCount")
if(!exceedcount){
try {
setLoading(true)
axios
.get(constants.BASE_URL + "getexceedcount?token=" +token)
.then(response => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
}
catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})
.catch(error => {
console.log(error);
});
} catch(error) {
console.log(error);
}
}else{
setExceedCount({ value:exceedcount, error: '' })
}
}
I don't know why this issue occured. Any help is appreciable.
You need to notate the function as async.
.then(async (response) => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
}
catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})
The scope of the function inside .then is not declared as async. This should fix your problem:
.then(async response => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
} catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})
I'm using React.useEffect() to retrieve the users list.
React.useEffect(() => {
dispatch(UsersActions.creators.fetchingUsersAction());
UsersApi.methods.getUsers().then(
(res) => {
dispatch(UsersActions.creators.fetchUsersSuccessAction(res.data));
},
(e) => {
dispatch(UsersActions.creators.fetchUsersErrorAction());
}
);
}, [dispatch]);
On this example, fetchingUsersAction is used to set "loading" to true, and fetchUsersErrorAction to false. This works fine, except when the request fails due to token expiration.
ApiClient.interceptors.response.use(
function (response) {
return response;
},
function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refresh = JSON.stringify({
refreshToken: localStorage.getItem("refresh"),
});
AuthenticationApi.methods.refresh(refresh).then((res) => {
if (res.data.accessToken) {
localStorage.setItem("token", res.data.accessToken);
}
ApiClient.defaults.headers.common["Authorization"] =
"Bearer " + res.data.accessToken;
originalRequest.headers["Authorization"] =
"Bearer " + res.data.accessToken;
return ApiClient(originalRequest);
});
}
return Promise.reject(error);
}
);
This is sending a request to generate a new token and the previous request, but since the first request failed, the useEffect is going to the error section, making the "loading" false and showing the users list based on the previous state. What is the best way to deal with this problem?
Thanks
You should create an Async fucntion inside useEffect hook and use await to wait for the response, then call the function. Here is one example:
useEffect(() => {
const getRoles = async () => {
await authService.roles().then((res) => {
//Do your stuff.
console.log(res);
}).catch((error) => {
console.log(`'Catching the error: '${error}`);
});
};
//Call the recent created function.
getRoles();
}, []);
Your interceptor looks good to me.
I am using redux approach in react js.I am calling getRolesPagination()
with service getRolesPagination() and pass handleResponse() in service to catch response/error.
It is working fine but when the server respond with 401 status error it doesn't catch the error.
I have to catch it to log out user because if user token get invalidate then the server responds with 401 status and
"{error :Unauthorized}"
function getRolesPagination(page, filter, sort, pageSize){
return dispatch => {
dispatch(request())
roleService.getRolesPagination(page, filter, sort, pageSize)
.then(
response => {
dispatch(success(response));
},
error => {
dispatch(failure(error));
dispatch(alertActions.error(error));
}
);
};
function request() { return { type: adminConstants.PAGINATION_ROLES_REQUEST } }
function success(response) { return { type: adminConstants.PAGINATION_ROLES_SUCCESS, payload:response } }
function failure(error) { return { type: adminConstants.PAGINATION_ROLES_FAILURE, payload:error } }
}
roleService.getRolesPagination function:
function getRolesPagination(page, filter, sort, pageSize){
const requestOptions = {
method : 'GET',
headers : authHeader()
};Why 401 errors is not getting caught with the fetch function in reactJS?
return fetch(baseUrl+'roles?page='+page+'&filter='+filter+'&sort='+sort+'&pageSize='+pageSize, requestOptions).then(handleResponse);
}
handleResponse function:
export function handleResponse(response) {
return response.json().then(data => {
if (!response.ok) {
if (response.status === 401) {
localStorage.removeItem('user');
window.location.reload(true);
}
const error = (data && data.error) || response.statusText;
return Promise.reject(error);
}
return data;
});
}
please check the status of the response, 401 is a valid server response it won't go to catch block
fetch(request)
.then(function(response) {
if (response.status !== 200) {
/*your code */
}else{
throw new Error(response.status)
}
})
.catch(function(error) {
/*logout logic*/
});