xhr.onprogress not working or not showing console - request

My code:
let xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText)
}else if (xhr.status===404){
console.log('Not found!')
}
}
}
xhr.addEventListener('progress',()=>{
console.log("Progressing")
})
xhr.onprogress=()=>{
console.log("Progressing")
}
xhr.open('GET', 'msg.txt', false)
xhr.send()
I tried 2 method for onprogress:
xhr.addEventListener('progress',()=>{
console.log("Progressing")
})
xhr.onprogress=()=>{
console.log("Progressing")
}
anyone not worked
osjdsdmskmdsddknsdnskdnkjsdnfjknsdkjfnkjdsnfknsdjfnkdsnfkjdsnfkndksjfnkjdnfkndnfsdsdsdsdsdsdsdsdsdsdsdsdfsdf

Related

After redirect to login page, show Toaster message

how to display this toster message after reloading the page in React js.
const store = configureStore();
let isLogout = false;
const handleResponse = (response) => {
if (response && response.data && response.data.status && response.data.status.code === 551 && !isLogout ) {
isLogout = true;
store.dispatch(actions.logout()).then(() => {
window.location.reload();
handleErrorMessageToastr("Authentication Fail")
});
}
return response
}

Match in React.js always returing nothing

Inside my Login class I have this piece of code :
state={email:'',passwordHash:''};
onButtonClick = () =>{
if(this.state.email==='' || this.state.passwordHash==='')
return;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
request.open('GET', 'http://localhost:8080/login/'+this.state.email+'/'+this.state.passwordHash, true);
request.send();
if(String(request.responseText).match("true"))
{
console.log("Inside Match");
window.location.href = '/home';
}
};
And in the console I get this :
As I'm getting true in the console, I should also get Inside Match in the console and then redirect, but that is not happening.
Can anyone help me with this problem ?
I have also tried === , == , single quote.
The onButtonClick function should be like this :
onButtonClick = () =>{
if(this.state.email==='' || this.state.passwordHash==='')
return;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
if(String(request.responseText).match("true"))
{
console.log("Inside Match");
window.location.href = '/home';
}
}
};
request.open('GET', 'http://localhost:8080/login/'+this.state.email+'/'+this.state.passwordHash, true);
request.send();
};
So when it gets data in response, it will redirect to another page, or console log or whatever. But it should be done inside that async function onreadystatechange.

reactjs call a function

I have a class API with a function which I wish to call in my component.
export default function(authentification){
axios.post('/login',params)
.then(response=> {
localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
localStorage.setItem(IS_AUTHENTICATED, true);
this.setState({isAuthenticated:true});
})
.catch(error =>{
const statusCode = error.response.status;
if(statusCode === 401)
errors.authentification = true;
else if (statusCode === 404)
errors.resource = true;
else
errors.server = true;
this.setState({errors});
});
}
I do not arrive in found how to call this function in my component and as to get back its result to put it in setState
First: separate your setState from your api helper method like:
export default function(authentification){
axios.post('/login',params)
.then(response=> {
localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
localStorage.setItem(IS_AUTHENTICATED, true);
return {status: "ok"}
})
.catch(error =>{
const statusCode = error.response.status;
if(statusCode === 401)
errors.authentification = true;
else if (statusCode === 404)
errors.resource = true;
else
errors.server = true;
return {status: "error", errors}
});
}
Or if you want to use a async/await syntax in your api method:
const authentification = async (params) => {
const response = await axios.post('/login',params);
const statusCode = response.status;
if (statusCode >= 200 && statusCode < 300) {
localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
localStorage.setItem(IS_AUTHENTICATED, true);
return {status: "ok"}
}
let errors = {};
if (statusCode === 401) {
errors.authentification = true;
}
else if (statusCode === 404) {
errors.resource = true;
}
else {
errors.server = true;
}
return {status: "error", errors}
}
export default authentification;
Then call you api function inside of componentDidMount() lifecycle method of your Component like:
...
componentDidMount = async () => {
let resp = await helperfunction();
if (resp.status === "ok") {
this.setState({isAuthenticated:true});
return;
}
this.setState({resp.errors});
}
...
in a file.js create all function you want and export it
let xxx = (authentification) => {
axios.post('/login',params)
.then(response=> {
localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
localStorage.setItem(IS_AUTHENTICATED, true);
this.setState({isAuthenticated:true});
})
.catch(error =>{
const statusCode = error.response.status;
if(statusCode === 401)
errors.authentification = true;
else if (statusCode === 404)
errors.resource = true;
else
errors.server = true;
this.setState({errors});
});
}
export default xxx;
then import it where you wanna use it like so --> import xxx from 'path';
I restructured my code. I do not know if it is the good architecture to employee. But I does not obtain answer in my component yet
Classe AuthentificationAPI :
import axios from "axios";
const AuthentificationAPI = {
login(params){
return axios.post('/login',params);
},
}
export {AuthentificationAPI as default}
AuthentificationService :
import { ACCESS_TOKEN, IS_AUTHENTICATED } from "constants/constants.js";
import AuthentificationAPI from "api//authentificationAPI.js";
const AuthentificationService = {
login(params){
let errors = {};
AuthentificationAPI.login(params).then(response => {
localStorage.setItem(ACCESS_TOKEN, response.headers.authorization);
localStorage.setItem(IS_AUTHENTICATED, true);
return {isAuthenticated:true};
})
.catch(error => {
const statusCode = error.response.status;
if(statusCode === 401)
errors.authentification = true;
else if (statusCode === 404)
errors.resource = true;
else
errors.server = true;
return errors;
});
},
}
export {AuthentificationService as default}
Call in my component :
let resp = AuthentificationService.login(params);
console.log(resp);

ping in React native

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);
})

reactJS how to stop it listening to ajax request

I have ajax call in componentdidmount. And and then setState inside the ajax promise.
The code is like this
componentDidMount(){
axios.post('mydomian.com/item/',this.state)
.then(function (response) {
const res = response.data
if (res.status === 'OK') {
this.setState({items :res.list})
}else{
console.log('can not load data', response)
}
}.bind(this))
}
componentWillUnmount(){
how to stop everything about axios?
}
This causes error 'can not setstate on an unmounted component', when I navigate to other route.
So I think what I should do is remove axios listener in the componentwillunmount. How to would you do it?
A very simple solution could be to set a flag on unmount and utilize it within the promise resolution, like so:
componentDidMount(){
axios.post('mydomian.com/item/',this.state)
.then(function (response) {
if (this.unmounted) return;
const res = response.data
if (res.status === 'OK') {
this.setState({items :res.list})
}else{
console.log('can not load data', response)
}
}.bind(this))
}
componentWillUnmount(){
this.unmounted = true;
}
I have find a great solution that has been defined by istarkov
const makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then((val) =>
hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
);
promise.catch((error) =>
hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
How to use:
const somePromise = new Promise(r => setTimeout(r, 1000));
const cancelable = makeCancelable(somePromise);
cancelable
.promise
.then(() => console.log('resolved'))
.catch(({isCanceled, ...error}) => console.log('isCanceled', isCanceled));
// Cancel promise
cancelable.cancel();
the solution has been found there.
My implementation.
Inside my function
const promiseShareByEmail = makeCancelable(this.props.requestShareByEmail(obj.email, obj.url));
promiseShareByEmail.promise.then(response => {
const res = response.data;
if (res.code != 0)
throw new Error(res.message);
this.setState({
message: {
text: TextMeasurements.en.common.success_share_test,
code: Constants.ALERT_CODE_SUCCESS
}
});
}).catch(err => {
if (err.isCanceled)
return;
this.setState({
message: {
text: err.message,
code: Constants.ALERT_CODE_ERROR
}
})
});
this.promiseShareByEmail = promiseShareByEmail;
this.props.requestShareByEmail(obj.email, obj.url) that function returns promise from axios.
when component will unmount cancel function should be invoked.
componentWillUnmount() {
this.promiseShareByEmail.cancel();
}
enjoy.

Resources