Routing back with in a time frame - vue.js

I am new to coding.In my app after the submission of a form i will get a message that i have submitted successfully or is it an error.After getting the message i want to revert back the user to my previous page with in 5 seconds.while using $router.push getting 'can not read property of undefine push'If some one knows please...
this the scrip to call
enter code here
methods: {
submitForm() {
formService.hospital({
firstName: this.firstName,
,
date: new Date(this.date),
time: this.time
}) .then(response => {
response.data;
console.log(response);
this.isSuccessMessage = true;
this.isErrorMessage = false;
this.$store.dispatch('addPickupAssistanceMessage');
setTimeout(function(){ this.$router.push('/dashboard'); 5000 });
}).catch(error => {
console.log("Error reported from endpoints :", JSON.stringify(error.response));
this.isErrorMessage = true;
this.$store.dispatch('addErrorMessage')
return (this.errorMessage = JSON.stringify(
error.response.data.errorMessage
))
});
},

The problem is inside the handler function passed to setTimeout, which uses this.$router, which is a property of the instance. The problem can be solved with arrow functions.
setTimeout(() => { this.$router.push('/dashboard'); }, 5000);

Related

Unhandled Promise Rejection when trying to call external function from async function

The error message:
WARN Possible Unhandled Promise Rejection (id: 1):
Error: INVALID_STATE_ERR
send#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:31745:26
initialiseWebsocket#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:100544:21
loadUserData$#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:100610:40
tryCatch#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:7739:23
invoke#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:7912:32
tryCatch#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:7739:23
invoke#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:7812:30
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:7822:21
tryCallOne#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:28596:16
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:28697:27
_callTimer#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:29113:17
_callImmediatesPass#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:29152:17
callImmediates#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:29370:33
__callImmediates#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:3279:35
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:3057:34
__guard#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:3262:15
flushedQueue#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dcgymappfrontend&modulesOnly=false&runModule=true:3056:21
flushedQueue#[native code]
invokeCallbackAndReturnFlushedQueue#[native code]
The useEffect that is being accused of being a problem:
React.useEffect(() => {
// Fetch the token from storage then navigate to our appropriate place
const loadUserData = async () => {
let userData;
try {
userData = await retrieveUserData();
} catch (e) {}
if(userData){
dispatch({ type: 'RESTORE_USER_DATA', userData: userData });
getChatData(userData, setChats, dispatch);
if(userData && !websocketInitialised){
console.log('web init called from *load user data*')
setWebsocketInitialised(true)
initialiseWebsocket(userData);
}
}
else{
dispatch({ type: 'RESTORE_USER_DATA_FAILED'});
}
};
loadUserData();
}, []);
The initialliseWebsocket function
function initialiseWebsocket(userData){
console.log('sending websocket initialisation data.');
websocket.send(JSON.stringify({
'action': 'init',
'data' : {'token': userData.token}
}));
}
the useState that is used above
const [websocketInitialised, setWebsocketInitialised] = React.useState(false);
async function getChatData(userData, setChats, dispatch){
console.log("fetching chat data");
// if we fail to download chat data, pull the old one from FS
const loadOldChatData = async () => {
let chats;
try {
chats = await retrieveChats();
} catch (e) {}
if(chats){
setChats(chats);
console.log("loaded cached chat data") ;
}
else{
setChats([]);
}
};
const onSuccess = (response) => {
if(response['chats']){
storeChats(response['chats']);
setChats(response['chats']);
console.log("chat data synced");
}
else{
loadOldChatData();
}
};
const onFailure = (response) => {
loadOldChatData();
};
fetch(Settings.siteUrl + '/messenger/get_chats/', {
method: "GET",
headers: {
"Content-type": "application/json; charset=UTF-8",
"Authorization": "Token " + userData.token
},
})
.then(response => response.json())
.then(response => {onSuccess(response)})
.catch(response => {onFailure(response)})
}
retrieveUseData() is most likely not the problem as this only started occuring after I added the other code.
Am I not supposed to use states like this or am I supposed to use the async key worked on functions? I tried that but I still have the same issue. You can see on the 4 line of the errors it mentions the 'initialiseWebsocket' function. I am guessing that is the route cause. I assume the solution will be some async version of it...
This error tell us that you didn't or forget to handle error from async code.
I refectory your code a bit, Tell me if you got any error message from console.log(error);
React.useEffect(() => {
// Fetch the token from storage then navigate to our appropriate place
(async () => {
try {
let userData = await retrieveUserData();
dispatch({ type: 'RESTORE_USER_DATA', userData });
await getChatData(userData, setChats, dispatch);
if (websocketInitialised) return;
console.log('web init called from *load user data*')
setWebsocketInitialised(true)
initialiseWebsocket(userData);
} catch (error) {
console.log(error);
dispatch({ type: 'RESTORE_USER_DATA_FAILED' });
}
})();
}, []);
And you should rename getChatData to setChatData, I also simplify those code also...
async function getChatData(userData, setChats, _dispatch) {
try {
let response = await fetch(Settings.siteUrl + '/messenger/get_chats/', {
method: "GET",
headers: {
"Content-type": "application/json; charset=UTF-8",
"Authorization": "Token " + userData.token
},
}),
data = await response.json(),
chats = data['chats'];
if (!chats?.length) throw "empty chat data, pull the old one from FS";
storeChats(chats);
setChats(chats);
} catch (_) {
// if we fail to download chat data, pull the old one from FS
await retrieveChats()
.then(chats => setChats(chats))
.catch(() => setChats([]))
}
}
"I don't really understand what you are doing with the async stuff."
async/await is just syntax sugar of promise, It allow you to work with async operation in a synchronous manner, some rules of async/await
In other to use await keyword, you need an async function.
you can make any function asynchronous, just by adding async keyword
async function always return promise
Lets see an example:
let delay = (ms, msg, bool) => new Promise((res, rej) => setTimeout(!bool ? res : rej , ms,msg));
This helper function create a promise for our example, it take 3 arguments, it take millisecond as 1st arg, to delay, 2rd is the message as payload. 3nd is Boolean; it true, then it will reject.
let delay = (ms, msg, bool) => new Promise((res, rej) => setTimeout(!bool ? res : rej, ms, msg));
let log = console.log;
async function myAsyncFn() {
let hello = await delay(100, "hello,");
let world = await delay(300, " world!");
// we use a symbol '#' to indicate that, its from `myAsyncFn`
log("#" , hello + world, "printed from async operation");
}
myAsyncFn();
log("As you can see that, this message print first");
// we are creating an async function and called immediately, In other to use `await keyword`
(async () => {
try {
let resolved = await delay(300,"resolved");
console.log(">" , `it ${resolved}!`);
// this will reject and catch via `try/catch` block;
let _ = await delay(600, "Error", true);
log("It will not print!");
// ...
} catch (error) {
log(">" , `we can catch "${error}" with try/catch, as like any sync code!`);
}
})()
As you can see that with async/await its look like everything is synchronous right? even everything execute asynchronously!
You just need to use await keyword to make every async operation synchronous.

How do i add another function in vue.js

How do i add multiple get posts in Vue.js.
I already have one post that I'm getting fine but I'm not sure how to add multiple post functions.
This is what i have so fare.
<script>
new Vue({
el: '#app',
data () {
return {
searchQuery: null,
info: null,
loading: true,
errored: false
}
},
mounted: function () {
axios.post('https://api.npms.io/v2/search?q=vue')
.then(response => {
this.info = response.data
console.log(this.info)
})
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
}
})
</script>
If you want to do the calls one after the other then
you can just nest the second axios call inside the first one.
In this way you can keep nesting to multiple levels
axios.post('https://api.npms.io/v2/search?q=vue').then(response => {
this.arrayOne = response.data
axios.post('https://api.npms.io/v2/search?q=vue').then(
response => this.arrayTwo = response.data
);
});
OR
You can try using async/await
Below is an example where I have used the response of first request to make the second request.
async mounted() {
try {
const response1 = await axios.get('/user/12345');
this.arrayOne = response1.data;
const response2 = await axios.get(`/user/12345/${this.arrayOne.name}/permissions`);
this.arrayTwo = response2.data;
} catch(e) {
console.log(e);
}
}
I would suggest taking a look at Promise.all() (link to MDN docs). You could do something like:
Promise.all([
axios.post('https://api.npms.io/v2/search?q=vue'),
axios.post('https://example.com/...')
]).then(responses => {
console.log(responses);
// will output an array with responses[0] equals to the data of the first call and responses[1] equals to the data of the second call
})
// Add your catch and finally clauses here...
The benefits of this approach is that your calls are made in parallel but the then clause will only be reached when they both ended.

Proper setup of Vue.js methods to deal with Axios asynchronous request

I have Vue.js app that fetch some complex data from API with Axios and then visualize this data.
My code looks similar to this:
{
data: () => ({
data: null, // or Object, it doesn't matter now
loading: false,
errored: false,
loadingMessage: ''
}),
methods: {
loadData: function() {
this.loading = true;
this.loadingMessage = 'Fetching Data';
axios.get('api/url/').then((response) => {
this.data= response.data; // or this.$set(this, 'data', response.data), it doesn't matter now
this.loadingMessage = 'Process Data';
this.processData();
})
.catch(function () {
this.errored= true;
})
.then(function () {
this.loading = false;
})
},
processData: function() {
// process data
}
}
}
So then I click on the button in template, this button calls loadData() function.
It works fine, but fetching data takes some time and processing also takes some time and Vue change template and variables only when axios request is finished. So I see only Fetching Data message but not Process Data.
How can I show the user at what stage of processing the data now?
Maybe I should call the processData() function in watch methods, but that seems overkill to me.
Update
I ended up with setTimeout() wrap. See my answer below.
Vue has a function called nextTick, which is an asynchronous function that basically means "perform the following code after the next visual update". I usually use this method if I have visual updates like this to make.
I think the code in your example would look like this:
axios
.get('api/url/')
.then((response) => {
this.data= response.data;
this.loadingMessage = 'Process Data';
return this.$nextTick();
})
.then(() => {
this.processData();
})
.catch (etc ...
I am not completely sure. I usually work in webpack/babel-enabled environments, in which case I would just make the whole function async and write:
async function fn() {
const response = await axios.get('api/url/');
this.data = response.data;
this.loadingMessage = 'Process Data';
await this.$nextTick();
this.processData();
}
You can read about it here (https://v2.vuejs.org/v2/guide/reactivity.html#Async-Update-Queue)
Can you try changing your function as follows:
loadData: function() {
this.loading = true;
this.loadingMessage = 'Fetching Data';
axios.get('api/url/').then((response) => {
this.data= response.data; // or this.$set(this, 'data', response.data), it doesn't matter now
this.$nextTick(() => {
this.loadingMessage = 'Process Data';
this.processData();
})
})
.catch(function () {
this.errored= true;
})
.then(function () {
this.loading = false;
})
},
I tried to use $nextTick(), as #joachim-bøggild advised me. I even tried to use $forceUpdate() to archieve this goal. But for some reason that was not clear to me, the effect I needed was not observed. The console showed that the value has changed. But on the screen and in Vue Devtools old results were shown until the request was completed.
So I decided to supplement the question with an example and started to create demo on JsFiddle. To show the rendering delay that I need, I used setTimeout(() =>{ this.loading = false}, 1000) and there were no problems at all.
I ported this approach to my code and everything worked perfectly. Until I tried to remove this setTimeout(). The problem arose again.
Therefore, in the end, I ended up on this code design:
...
axios.get('api/url/').then((response) => {
this.data= response.data;
this.loadingMessage = 'Process Data';
setTimeout(() => {
this.processData();
this.loading = false;
}, 10); // if this value less than 10 error still occurs
})
.catch(function () {
this.errored= true;
})
...
If someone understands why this behavior is happening, please complete my answer.

Vue Switch showing always off

When I click on the edit button on my page edit form is opened and it contains some switches. I am getting value '1' from DB but in the edit form switch is always off. How can I resolve this?
edit.vue
<d-field-group class="field-group field-row" label-for = "Zip_Need" label="Does it need zip/postal code?" label-class="col-4">
<d-switch id="Zip_Need" name="Zip_Need" v-model="form.Zip_Need" ></d-switch>
</d-field-group>
Script
editCountry(id){
axios.defaults.headers.common['Authorization'] = "Bearer "+localStorage.getItem('token');
axios.get(baseUrl+'/country/edit/'+id)
.then((response) => {
this.form = response.data[0].form;
setTimeout(() => {
this.subComponentLoading = true;
}, 500);
})
.catch(function (error) {
console.log(error);
});
},

Doing a Timeout Error with Fetch - React Native

I have a user login function that is working. But, I want to incorporate a time out error for the fetch. Is there a way to set up a timer for 5 seconds or so that would stop trying to fetch after such a time? Otherwise, I just get a red screen after a while saying network error.
_userLogin() {
var value = this.refs.form.getValue();
if (value) {
// if validation fails, value will be null
if (!this.validateEmail(value.email)) {
// eslint-disable-next-line no-undef
Alert.alert('Enter a valid email');
} else {
fetch('http://51.64.34.134:5000/api/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
timeout: 5000,
body: JSON.stringify({
username: value.email,
password: value.password,
}),
})
.then((response) => response.json())
.then((responseData) => {
if (responseData.status == 'success') {
this._onValueChange(STORAGE_KEY, responseData.data.token);
Alert.alert('Login Success!');
this.props.navigator.push({name: 'StartScreen'});
} else if (responseData.status == 'error') {
Alert.alert('Login Error', responseData.message);
}
})
.done();
}
}
}
I have made a ES6 function that wraps ES fetch into a promise, here it is:
export async function fetchWithTimeout(url, options, timeout = 5000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout))
]);
}
Here is how to use it:
const requestInfo = {
method,
headers,
body,
};
const url = 'http://yoururl.edu.br'
let data = await fetchWithTimeout(url, requestInfo, 3000);
// Wrapper function for fetch
const fetchSomething = async () => {
let controller = new AbortController()
setTimeout(() => controller.abort(), 3000); // abort after 3 seconds
const resp = await fetch('some url', {signal: controller.signal});
const json = await resp.json();
if (!resp.ok) {
throw new Error(`HTTP error! status: ${resp.status}`);
}
return json;
}
// usage
try {
let jsonResp = await fetchSomthing();
console.log(jsonResp);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Network Error');
} else {
console.log(error.message);
}
}
I think using AbortController is the recommended way to abort a fetch call. The code snippet above handles the following scenarios:
If network is good but HTTP returns an error status, the message "HTTP error! ..." will be logged.
If network is down, setTimeout would trigger the AbortController to abort fetch after three seconds. The message "Network Error" will be logged.
If network is good and HTTP response is good, the response JSON will be logged.
The documentation for using AbortController to abort fetch is here.
There is no standard way of handling this as a timeout option isn't defined in the official spec yet. There is an abort defined which you can use in conjunction with your own timeout and Promises. For example as seen here and here. I've copied the example code, but haven't tested it myself yet.
// Rough implementation. Untested.
function timeout(ms, promise) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error("timeout"))
}, ms)
promise.then(resolve, reject)
})
}
timeout(1000, fetch('/hello')).then(function(response) {
// process response
}).catch(function(error) {
// might be a timeout error
})
Another option would be to modify the fetch.js module yourself to add a timeout that calls abort as seen here.
This is what I did to go around it:
(This is the "generic" function I use to make all calls on my app)
I created a timeout function, that will be triggered unless it is cleared before, then I clear this timeout on server response
const doFetch = (url, callback, data) => {
//... creating config obj here (not relevant for this answer)
var wasServerTimeout = false;
var timeout = setTimeout(() => {
wasServerTimeout = true;
alert('Time Out');
}, 3000);
fetch(HOST + url, config)
.then((response) => {
timeout && clearTimeout(timeout); //If everything is ok, clear the timeout
if (!wasServerTimeout) {
return response.json();
}
})
.then((response) => {
callback && callback(response.data || response);
})
.catch((err) => {
//If something goes wrong, clear the timeout
timeout && clearTimeout(timeout);
if (!wasServerTimeout) {
//Error logic here
}
});
};
I solved this problem by using a race between 2 promises, written as a wrapper around fetch. In my case I expect the request to return json so also added that. Maybe there is a better solution, but this works correctly for me!
The wrapper returns a promise which will resolve as long as there are no code errors.
You can check the result.status for 'success' and read json data from result.data. In case of error you can read the exact error in result.data, and display it or log it somewhere. This way you always know what went wrong!
var yourFetchWrapperFunction = function (
method,
url,
headers,
body,
timeout = 5000,
) {
var timeoutPromise = new Promise(function (resolve, reject) {
setTimeout(resolve, timeout, {
status: 'error',
code: 666,
data:
'Verbinding met de cloud kon niet tot stand gebracht worden: Timeout.',
});
});
return Promise.race([
timeoutPromise,
fetch(connectionType + '://' + url, {
method: method,
headers: headers,
body: body,
}),
])
.then(
(result) => {
var Status = result.status;
return result
.json()
.then(
function (data) {
if (Status === 200 || Status === 0) {
return {status: 'success', code: Status, data: data};
} else {
return {
status: 'error',
code: Status,
data: 'Error (' + data.status_code + '): ' + data.message,
};
}
},
function (response) {
return {
status: 'error',
code: Status,
data: 'json promise failed' + response,
};
},
)
.catch((error) => {
return {status: 'error', code: 666, data: 'no json response'};
});
},
function (error) {
return {status: 'error', code: 666, data: 'connection timed out'};
},
)
.catch((error) => {
return {status: 'error', code: 666, data: 'connection timed out'};
});
};
let controller = new AbortController()
setTimeout( () => {
controller.abort()
}, 10000); // 10,000 means 10 seconds
return fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(param),
signal: controller.signal
})
I may be late but i made a code which is 100% working to timeout an API request using fetch.
fetch_timeout(url, options) {
let timeout = 1000;
let timeout_err = {
ok: false,
status: 408,
};
return new Promise(function (resolve, reject) {
fetch(url, options)
.then(resolve, reject)
.catch(() => {
alert('timeout.');
});
setTimeout(reject.bind(null, timeout_err), timeout);
});
}
You just need to pass the api-endpoint to the url and body to the options parameter.