I want to know about vue asynchronous update - vue.js

I want to output the data obtained from the server to the screen as an asynchronous update.
There is no default value, but I want to print it when it is different from the new one.
methods: {
message : function(){
},
updateMessage: function () {
const path = 'http://localhost:5000/process';
axios.get(path)
.then((res) => {
this.msg = res.data;
})
.catch((error) => {
// eslint-disable-next-line
console.error(error);
});
},
},
created() {
this.message();
this.$nextTick();
this.$forceUpdate();
}
};
There is no reaction.

In your example code you never call the updateMessage() function.
new Vue({
el: "#app",
data: {
msg: ''
},
methods: {
message: function() {},
updateMessage: function() {
const path = 'https://jsonplaceholder.typicode.com/posts/1';
axios.get(path)
.then((res) => {
this.msg = res.data.title;
})
.catch((error) => {
// eslint-disable-next-line
console.error(error);
});
},
},
created() {
this.message();
this.updateMessage();
this.$nextTick();
this.$forceUpdate();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>MSG: {{msg}}</div>
</div>

Related

Problems with vuex: Uncaught (in promise) TypeError: _ctx.getProduct.image_url is undefined

I'm trying to load a product's data, passing props through the Vue Router, this is my code:
...store/modules/products_manager.js
import axios from 'axios';
const BASE_URL = "http://127.0.0.1:3000/"
const state = {
product: [],
products: [],
category: "",
}
const getters = {
getProducts(state) {
return state.products;
},
getProduct(state) {
console.log("GET")
console.log(state.product)
return state.product;
},
getCategory(state) {
return state.category;
},
}
const actions = {
getAllProducts({ commit }, payload) {
const config = {
params: {
title: payload['name']
}
}
new Promise((resolve, reject) => {
axios
.get(`${BASE_URL}products/`, config)
.then((response) => {
commit("setProducts", response);
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
},
getProductById({ commit }, payload) {
new Promise((resolve, reject) => {
axios
.get(`${BASE_URL}products/${payload}`)
.then((response) => {
commit("setProduct", response);
console.log("PRODUCT")
console.log(response.data)
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
},
getCategoryById({ commit }, payload) {
new Promise((resolve, reject) => {
axios
.get(`${BASE_URL}categories/${payload}`)
.then((response) => {
commit("setCategory", response);
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
},
}
const mutations = {
setProducts(state, data) {
state.products = data.data;
},
setProduct(state, data) {
console.log("SET")
console.log(data.data)
state.product = data.data;
},
setCategory(state, data) {
state.category = data.data;
},
}
export default {
state,
getters,
actions,
mutations,
}
../components/ProductPage.vue
<template lang="">
<div>
<p v-if="(getProduct != null || getProduct != undefined)" >{{ getProduct['image_url'][0] }}</p>
</div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex';
export default {
name: 'Product',
props: ["id", "category_id"],
computed: {
...mapGetters(["getProduct", "getCategory"]),
},
mounted() {
console.log(this.id)
console.log(this.category_id)
this.$store.dispatch("getProductById", this.id)
this.$store.dispatch("getCategoryById", this.category_id)
}
}
</script>
But I'm having some problems, I'm starting with vuex and I'm not understanding many things yet.
Error Printscreen
I did some tests, I used functions like created, updated, etc. With some of them, the information was even displayed on the screen, but it still generated the same errors. I believe it must be some error in the vue data flow, but I still don't understand how to solve it.
Sorry my bad english ;)
Solution:
<div>
<p v-if="(getProduct['image_url'] != null || getProduct['image_url'] != undefined)" >{{ getProduct['image_url'][0] }}</p>
</div>
Thank's #yoduh

Vuejs Vuex sometimes initial state not working Error: [Vue warn]: Error in render: "TypeError: Cannot read property 'Any_Variable' of undefined"

Other pages are working fine. Only facing issue with this file. May be I am coding wrong.
Store file is included in app.js file as other pages are working I have not included it.
Here Sometimes I get undefined MDU_Number. Sometimes it work fine. I am new to vue js.
Image of error that I am receving:
This is my vue template
<div class="card-body">
<div class="form-group row">
<label class="col-sm-4 col-form-label">MDU Number</label>
<div class="col">
<input
name="MDU_Number"
:value="mduprofile.MDU_Number"
#input="updateMDUNumber"
type="text"
class="form-control"
placeholder="Enter MDU Number Ex:GJXXCHXXXX"
required
/>
</div>
</div>
</div>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
data() {
return {
};
},
created() {
this.fetchForMDU();
},
destroyed() {
this.resetState();
},
computed: {
...mapGetters("MDUSingle", [
"loading",
"country",
"area",
"product",
"mduprofile",
]),
},
methods: {
...mapActions("MDUSingle", [
"resetState",
"fetchForMDU",
"storeMDU",
"setMDUNumber",
]),
submitForm() {
this.storeMDU()
.then(() => {
this.resetState();
this.$eventHub.$emit(
"create-success",
"Created",
"MDU created successfully"
);
})
.catch((error) => {
console.log(error);
});
},
updateMDUNumber(e) {
this.setMDUNumber(e.target.value);
},
},
};
</script>
This is store file name single.js and I have included it in app.js file
MDU_Number should go for null value but it goes for undefined. So I think it is not initialized properly. There are many other variables but for simplicity purpose I have included only one.
What can be the issue?
function initialState() {
return {
mduprofile: {
MDU_Number: null,
},
country: [],
area: [],
product: [],
loading: false
};
}
const getters = {
country: state => state.country,
area: state => state.area,
product: state => state.product,
loading: state => state.loading,
mduprofile: state => state.mduprofile
}
const actions = {
fetchForMDU({ commit }) {
return new Promise((resolve, reject) => {
axios.get('/get/detail/for/mdu')
.then((response) => {
let detail = response.data;
commit('setCountryAll', detail.country);
commit('setStateAll', detail.state);
commit('setProductAll', detail.product);
}).catch(error => {
reject(error);
}).finally(() => {
resolve();
});
});
},
storeMDU({ commit, state, dispatch }) {
commit('setLoading', true);
dispatch('Alert/resetState', null, { root: true });
return new Promise((resolve, reject) => {
let params = _.cloneDeep(state.mduprofile);
axios.post('/save-mdu-profile', params)
.then((response) => {
resolve();
})
.catch(error => {
commit('setLoading', false);
let message = error.response.data.message || error.message;
let errors = error.response.data.errors;
dispatch('Alert/setAlert',
{ message: message, errors: errors, color: danger },
{ root: true });
reject(error);
}).finally(() => {
commit('setLoading', false);
});
});
},
fetchData({ commit }, value) {
axios.get('/mdu/profile/' + value)
.then((response) => {
commit('setAll', response.data.mdu);
}).catch(error => {
}).finally(() => {
});
},
updateMDU({ commit, state, dispatch }) {
commit('setLoading', true);
dispatch('Alert/setAlert', null, { root: true });
return new Promise((resolve, reject) => {
let params = _.cloneDeep(state.mduprofile);
axios.put('/update-mdu-profile/' + params.MDU_Id, params)
.then((response) => {
resolve();
}).catch(error => {
let message = error.response.data.message || error.message;
let errors = error.response.data.errors;
dispatch('Alert/setAlert',
{ message: message, errors: errors, color: danger },
{ root: true });
commit('setLoading', false);
reject(error);
}).finally(() => {
commit('setLoading', false);
});
});
},
resetState({ commit }) {
commit('resetState');
},
setMDUNumber({ commit }, value) {
commit('setMDUNumber', value);
}
}
const mutations = {
resetState(state) {
state = Object.assign(state, initialState());
},
setLoading(state, loading) {
state.loading = loading;
},
setCountryAll(state, items) {
state.country = items
},
setStateAll(state, items) {
state.area = items;
},
setProductAll(state, items) {
state.product = items;
},
setAll(state, items) {
state.mduprofile = items;
},
setMDUNumber(state, value) {
state.mduprofile.MDU_Number = value;
},
setCountry(state, value) {
state.mduprofile.Country = value;
},
setState(state, value) {
state.mduprofile.State = value;
},
setProduct(state, value) {
state.mduprofile.Product = value;
}
}
export default {
namespaced: true,
state: initialState,
getters,
actions,
mutations
}
Try checking somewhere where you change this values, if you don't catch error properly you may encounter empty states.

How to set a value inside a variable on data() using a function?

I'm creating a Vue.js component inside a Laravel App.
After I catch the response with an axios request, I can't put a value inside a variable on method data()
Here is the code:
app.js
require('./bootstrap')
window.Vue = require('vue')
Vue.component('card', require('./components/card.vue'))
let app = new Vue({
el: '#app'
})
card.vue
<script>
module.exports = {
props: [
'name'
],
data: function() {
return {
projects: [],
}
},
mounted() {
this.getProjects() // NOT WORK?
},
methods: {
getProjects: function() {
axios.get('/api/v1/getProjects').then(function (response) {
console.log(response.data)
this.projects = response.data // NOT WORK
}).catch(function (error) {
console.log(error)
}).then(function () {
})
},
}
}
</script>
It's because of using this in response callback. You should use an arrow function (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) or save the context in separate variable.
Try to add .bind(this) or replace function with =>:
getProjects: function() {
axios.get('/api/v1/getProjects').then((response) => {
console.log(response.data)
this.projects = response.data // NOT WORK
}).catch((error) => {
console.log(error)
}).then(function () {
})
},

How to bind data from an api function into data object in vue.js

I am performing a Axios.get() to a Weather API, in result i want to filter specific data of information about "current weather" etc.
<template lang="html">
<div id="weather">
{{weatherData}}
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
weatherData: {
stringSummary: this.weatherApi.data.currently.summary,
},
};
},
created() {
this.weatherApi();
},
methods: {
async weatherApi() {
axios.get('https://api.darksky.net/forecast/
89cef1a2abe989e0d09a4ebd75f02452/53.551085,-9.993682?
lang=de&units=si')
.then((response) => {
console.log(response);
return response;
})
.catch((error) => {
console.log(error);
});
},
},
};
</script>
Please check my "stringSummary" part inside Data. Shouldn't this work?
I am thankful for any help.
You should assign weatherData in then block:
methods: {
async weatherApi() {
axios.get('https://api.darksky.net/forecast/
89cef1a2abe989e0d09a4ebd75f02452/53.551085,-9.993682?
lang=de&units=si')
.then((response) => {
this.weatherData = {
stringSummary: response.data.currently.summary
}
return response;
})
.catch((error) => {
console.log(error);
});
},

Vue.js props not showing actual message value, What have I done and how can I solve it?

I am learning vue.js and for my practice purpuse I am making an chatting app. in my chatlog component I used props. when I print those property in console it's ok and print all the object in console but in templete they all are vanished. My code is bellow.
Thanks in advance.
Chatlog
<template>
<div class="chat-log">
<button #click="showOnConsole">Show on console</button>
<p>{{ messages}}</p>
</div>
</template>
<script>
export default {
props: ['messages'],
methods: {
showOnConsole()
{
console.log(messages);
}
}
}
</script>
app.js
const app = new Vue({
el: '#app',
data:{
messages: []
},
created: function() {
axios.get('/Chat/public/messages')
.then(function (response) {
this.messages = response.data;
})
.catch(function (error) {
console.log(error);
});
}
});
Rewrite your created method, so you bind your own this:
created: function() {
axios.get('/Chat/public/messages')
.then(response => {
this.messages = response.data;
})
.catch(function (error) {
console.log(error);
});
}
Or without using an arrow function:
created: function() {
var that = this
axios.get('/Chat/public/messages')
.then(function (response) {
that.messages = response.data;
})
.catch(function (error) {
console.log(error);
});
}