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);
});
},
Related
I want to get user's current location and set it into AsyncStorage a array. I will do it in the useEffect hook. But the problem is my functions are not working that according to given order. Here are my code
useEffect(() => {
getUserLocation();
setUserLocation();
check();
}, []);
/*Get User's Currunt Location*/
const getUserLocation = () => {
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000,
})
.then((location) => {
var lt = location.latitude;
var lg = location.longitude;
setlatitude(lt);
setlongitude(lg);
console.log("getUserLocation", lt, lg);
})
.catch((error) => {
const { code, message } = error;
console.warn(code, message);
});
};
/*Set User's Currunt Location to AsyncStorage*/
const setUserLocation = async () => {
try {
await AsyncStorage.setItem("user_location", JSON.stringify(userLocation));
console.log("setUserLocation", userLocation);
} catch (error) {
console.log("error setting user location");
}
};
const check = () => {
AsyncStorage.getItem("user_location", (err, result) => {
if (result !== null) {
console.log("check", result);
setlatitude(result.latitude);
setlongitude(result.longitude);
} else {
console.log("Data Not Found");
}
});
};
Whenever you use .then you are scheduling your code to run at some point in the future, when the promise has completed. So setUserLocation runs before the then of getUserLocation.
Also, it looks like your getUserLocation set react state, which won't be available until the next render. We use effects to manage this.
// Get the location on mount
useEffect(getUserLocation, []);
// Whenever the location updates, set it into storage
useEffect(() => setUserLocation().then(check), [latitude, longitude]);
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);
i already call the axios and show using console log if it is successful or not already, However i wanted to pass the axios post response value to my vue component and display the response in my vue component in order for me to make a condition. Is there any way to do it? I try some other part but no luck. Kindly guide me.
main.vue
methods: {
onClicked() {
this.$store
.dispatch('Clickme', this.data)
.then(() => {
alert("Success");
})
.catch(() => {
alert("Error");
})
}
}
clicked.js
return new Promise((resolve, reject) => {
clicked(username, password)
.then(resp => {
console.log("---->>>> : ");
const data = resp.data.data
console.log(username, password);
console.log(resp);
console.log("statresponse.status : " + resp.data.status);
console.log("statresponse.message : " + resp.data.message);
console.log("statresponse.inside message : " + resp.data.data.message);
// console.log("USER.JS RESPONSE: " + resp.data.status);
// console.log("USER.JS RESPONSE: " + resp.data.message);
setToken(data.token)
commit('SET_TOKEN', data.token)
resolve()
})
.catch(error => {
console.log(error)
reject(error)
})
})
Try changing main.vue to:
onClicked() {
this.$store
.dispatch('Clickme', this.data)
.then((response) => {
//Do whatever you want with your response
alert("Success");
})
.catch(() => {
alert("Error");
})
}
and change clicked.js to:
resolve(resp.data.data)
This will make so the promise resolves the response data.
However if you make the http request in your store/using vuex, what you probably want to do is commit a mutation to put the response into your state - and then map the state from your component.
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.
I am not sure what I am doing wrong, but I cant seem to open the dialog, but I am getting a {status: 'OK'} response...
Mattermost Version: 5.13.2
The post from the slash command is ephemeral
My slash command is working fine, and so is the interactive button (this is what should trigger the dialog to open).
Here is my code for the dialog to trigger. This req param is being passed from the action from clicking a button.
module.exports.addEmail = (req) => {
let body = req.body;
let data = JSON.stringify({
trigger_id : body.trigger_id,
url : resolve(config.MM_ACTION_URL, '/mattermost/dialog'),
dialog : {
title : 'Email',
callback_id : 'add_email',
elements : [
{
display_name : 'Email',
name : 'email',
type : 'text',
subtype : 'email',
placeholder : 'placeholder#example.com'
}
]
}
});
mmRequest('post', 'actions/dialogs/open', data)
.then((res) => {
console.log(res);
})
.catch((error) => console.log(error));
};
On the server side, this is my code to add a little more context to my workflow.
app.post('/mattermost/actions', (req, res) => {
// console.log(req.body);
let action = req.body.context.action;
if (action === 'add_email') {
dialog.addEmail(req);
}
});
app.post('/mattermost/dialog', (req, res) => {
console.log(req.body);
res.sendStatus(200);
});
And the function that is making the API call to the mattermost server is
module.exports.mmRequest = (method, url, data = {}) => {
let c = {
method : method,
baseURL : resolve(config.MATTERMOST_URL, 'api/v4/'),
url : url,
data : data,
headers : {
Authorization : `Bearer ${config.MM_ACCESS_TOKEN}`
}
};
return new Promise((resolve, reject) => {
Axios(c)
.then((res) => {
resolve(res.data);
})
.catch((error) => reject(error.response));
});
};
In the console.log(res), I get a status OK message, but the dialog doesnt open.. What am I doing wrong?