Match in React.js always returing nothing - reactjs

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.

Related

xhr.onprogress not working or not showing console

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

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
}

call a function from within eventListener

I want to call a function from within the eventListener
I get this error :
TypeError: this.foo is not a function
I understand that this is the xhr itself and not the class that wraps both function.
How can I call foo from within the eventListener callback?
createStripeUser = async (code) => {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
this.foo(this.responseText)
}
});
xhr.open("POST", "https://connect.stripe.com/oauth/token");
xhr.send(data);
}
foo = (data ) => {
console.log(data)
}
If you want access this from outside you need to use () => {} instead of function() {} in readyStateChange callback.
createStripeUser = async (code) => {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", () => {
if (xhr.readyState === 4) {
this.foo(xhr.responseText)
}
});
xhr.open("POST", "https://connect.stripe.com/oauth/token");
xhr.send(data);
foo = (data ) => {
console.log(data)
}
i don't know your code is a class or not. but if it not, just call foo(xhr.responseText) instead.
You must use a alias for this in callback for xhr like this:
const that=this;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
that.foo(this.responseText)
}
});

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

Resources