I am making a get request where I save the result in a variable called name_student. How can I show this variable in other methods? or how should I declare it?
This is my code:
getStudent(){
axios.get('https://backunizoom.herokuapp.com/student/2')
.then((result) => {
console.log(result.data)
this.name_student=result.data.name
console.log(name_student)
})
console.log(name_student)
},
Shared data props
As #scar-2018 suggested in comments, you just need to declare name_student as a data prop to make the prop available across all component methods and hooks:
export default {
data() {
return {
name_student: '',
}
},
methods: {
getStudent() {
axios.get(/*...*).then((result) => {
this.name_student = result.data.name
this.updateStudentName()
})
},
updateStudentName() {
this.name_student += ' (student)'
}
}
}
Accessing async data
You commented that you're seeing undefined when you log name_student. Assuming the code in your question does not have a typo with regards to the location of the console.log() calls, the axios callback is run asynchronously, and you're logging this.name_student before axios modifies it:
axios.get(/*...*/).then((result) => {
this.name_student = result.data.name
console.log(this.name_student) // => 'foo' ✅
})
console.log(this.name_student) // => undefined ❌ (not yet set)
Related
I have created an axios request to my api for two routes. Using the response data I sort posts into the correct columns inside an array. This all works as it should but then when I come to assigning the value of this array to an array inside data() i get the following error;
TypeError: Cannot set property 'boardPosts' of null
at eval (SummaryBoard.vue?2681:90)
at wrap (spread.js?0df6:25)
So I figured maybe something was wrong with the array I was trying to assign. So I tried to assign boardPosts a simple string value and I still get the same error. Why can I not set the value of boardPosts inside my axios response?
my code;
import axios from 'axios';
export default {
name: 'SummaryBoard',
data() {
return {
boardPosts: '',
}
},
created() {
this.getBoardData();
},
methods:
getBoardData() {
function getBoardColumns() {
return axios.get('http://localhost:5000/api/summary-board/columns');
}
function getBoardPosts() {
return axios.get('http://localhost:5000/api/summary-board/posts');
}
axios.all([getBoardColumns(), getBoardPosts()])
.then(axios.spread(function(columnData, postData) {
let posts = postData.data;
// add posts array to each object
let columns = columnData.data.map(obj => ({...obj, posts: []}));
posts.forEach((post) => {
// If column index matches post column index value
if(columns[post.column_index]){
columns[post.column_index].posts.push(post);
}
});
console.log(columns);
this.boardPosts = 'hello';
}))
.catch(error => console.log(error));
}
}
}
That's because you're using not using an arrow function in axios.spread(...). This means that you do not preserve the lexical this from the VueJS component, as function() {...} will create a new scope for itself. If you change it to use arrow function, then the this in the callback will refer to your VueJS component instance:
axios.all([getBoardColumns(), getBoardPosts()])
.then(axios.spread((columnData, postData) => {
// Rest of the logic here
}))
.catch(error => console.log(error));
I am trying to fetch news articles from an external source, it returns JSON object. I want to assign its articles property to a variable in my component. Somehow this error is occurring.
Uncaught (in promise) TypeError: Cannot set property 'articles' of undefined
Any suggestions on how to overcome this problem?
export default {
name: "blog",
data() {
return {
articles: [],
};
},
mounted() {
// API call
this.fetchnews();
},
methods: {
fetchnews(){
fetch(
"----------------------news link-------------------------"
)
.then(function(response) {
return response.json();
})
.then(function(json_data) {
//console.log(typeof(json_data))
this.articles = json_data.articles
});
}
}
};
As the first contributor properly noticed - the issue is this.articles inside your latest function doesn't really point to what you need.
If you are limited to ES5 then stick to the first answer.
However if you can use ES6 then simply get advantages of short syntax:
export default {
name: "blog",
data() {
return {
articles: [],
};
},
mounted() {
// API call
this.fetchnews();
},
methods: {
fetchnews(){
fetch("----------------------news link-------------------------")
.then(response => response.json())
.then(json_data => this.articles = json_data.articles);
}
}
};
in this case this will properly point to the outer scope.
Also why do you need two then()? You could collapse them into one:
.then(response => this.articles = response.json().articles);
using function keyword creates new scope. if you use arrow syntax like () => {} you can use parent scope and set articles via this.articles
fetchnews(){
fetch()
.then((response) => {
return response.json();
})
.then((json_data) => {
this.articles = json_data.articles
});
}
inthis.articles: here this refers to the function not vue instance , so you may define this outside the function like:
let This=this
and inside your function :
This.articles = json_data.articles
This here refers to vue instance
javascript function as global scope make sure use to assign function to variables
I am trying to set the breakfastMenu array in state as shown below but I can't see the array being filled in my vue-devtools.
I have properly set-up the Vuex methods and checked twice, also I didn't receive any sort of error. So, why do I have a logical error in my code?
store.js:
export default new Vuex.Store({
state: {
menu: [],
breakfastMenu: [],
lunchMenu: [],
dinnerMenu: []
},
mutations: {
'SET_MENU': (state, menuMaster) => {
state.menu = menuMaster;
},
'SET_BREAKFAST_MENU': (state, order) => {
state.breakfastMenu.unshift(order);
},
'SET_LUNCH_MENU': (state, order) => {
state.breakfastMenu.unshift(order);
},
'SET_DINNER_MENU': (state, order) => {
state.breakfastMenu.unshift(order);
},
},
actions: {
initMenu: ({ commit }, menuMaster) => {
commit('SET_MENU', menuMaster)
},
initBreakfastMenu: ({ commit, state }) => {
state.menu.forEach((element) => {
if (element.categoryId == 1) {
commit('SET_BREAKFAST_MENU', element)
}
});
},
initLunchMenu: ({ commit, state }) => {
state.menu.forEach((element) => {
if (element.categoryId == 2) {
commit('SET_LUNCH_MENU', element)
}
});
},
initDinnerMenu: ({ commit, state }) => {
state.menu.forEach((element) => {
if (element.categoryId == 3) {
commit('SET_DINNER_MENU', element)
}
});
},
},
getters: {
getBreakfastMenu(state) {
return state.breakfastMenu
},
getLunchMenu(state) {
return state.lunchMenu
},
getDinnerMenu(state) {
return state.dinnerMenu
},
}
})
Breakfast.vue:
import { mapActions, mapGetters } from 'vuex';
export default {
data() {
return {
breakfastArray: []
};
},
methods: {
...mapActions(['initBreakfastMenu']),
...mapGetters(['getBreakfastMenu']),
},
created() {
this.initBreakfastMenu;
this.breakfastArray = this.getBreakfastMenu;
}
};
No error messages so far!
I need the breakfastMenu array filled in store.js.
Please help out!
A few thoughts.
Firstly, this line:
this.initBreakfastMenu;
You aren't actually calling the method. It should be:
this.initBreakfastMenu();
Next problem is this:
...mapGetters(['getBreakfastMenu']),
The line itself is fine but it's inside your methods. It should be in the computed section.
You haven't included any sample data for state.menu but it's also worth noting that initBreakfastMenu won't do anything unless there is suitable data inside state.menu. I suggest adding some console logging to ensure that everything is working as expected there.
SET_BREAKFAST_MENU, SET_LUNCH_MENU and SET_DINNER_MENU are all modifying state.breakfastMenu. I would assume that this is incorrect and each should be modifying their respective menu.
I would also note that using local data for breakfastArray is suspicious. Generally you'd just want to use the store state directly via the computed property rather than referencing it via local data. This is not necessarily wrong, you may want to detach the component data from the store in this way, but keep in mind that both are referencing the same array so modification to one will also affect the other. You aren't taking a copy of the array, you're just creating a local reference to it.
You should also consider whether you actually need the 4 menu types within your state. If breakfastMenu, lunchMenu and dinnerMenu are all just derived from menu then you'd be better off just implementing those using getters. getters are the store equivalent of computed properties and can contain the relevant filtering logic to generate their value from state.menu.
initBreakfastMenu is an action and you may want to use this.initBreakfastMenu()
I have a strange problem in my Vue application.
The component looks like this:
...
<template v-for="foo in foos">
<Elm v-if="foo.visible" :key="foo.label" :bar="foo" />
</template>
...
"Elm" is a value in an object, retrieved from a JSON file.
The component is reactive if I get the JSON file locally:
<script>
import datas from "datafile.json";
...
methods: {
fillFoos() {
datas.forEach(data => {
this.foos.push(data)
})
}
},
mounted: {
this.fillFoos()
}
...
</script>
But when I retrieve the file remotely using fetch, the component is no longer reactive and no longer disappears when the foo.visible value is changed :
<script>
methods: {
getDataFromApi() {
return new Promise((resolve, reject) => {
fetch(this.apiUrl)
.then(response => {
return response.json();
})
.then(jsonResponse => {
resolve(jsonResponse);
})
.catch(e => {
...
})
})
},
fillFoos() {
this.getDataFromApi()
.then(response => {
response.forEach(data => {
this.foos.push(data);
});
});
}
},
mounted: {
this.fillFoos()
}
...
</script>
In both cases the "foos" array is correctly filled, the only difference is that the v-if directive seems to be broken in the second case.
To be more precise, the display is done correctly at initialization (foo.visible is true for all the elements and they're all displayed), but in case of a later change of the foo.visible value, they don't disappear.
I can't find what's wrong...
I believe the issue you are having is that the method getDataFromApi is returning a promise, but when you consume it in fillFoos the promise is not awaited, instead you call forEach on it.
You need to use the getDataFromApi().then(x => {}) syntax to resolve the promise, or alteratively you can use async await.
You can try something like this
methods: {
async getDataFromApi() {
const response= await fetch(this.apiUrl);
return response.json();
},
async fillFoos() {
try {
await foos = this.getDataFromApi();
this.foos = foos;
} catch(error) {
//handle error.
}
}
}
Someone posted a response very close to the solution yesterday but deleted it, I don't know why.
The problem was that I stored the fetch response in a variable in the data section, before using it to fill in the "foos" table
data: function() {
return {
dataFromApi: null
}
}
By removing this variable, and thus creating it on the fly after the fetch, everything works normally.... I didn't specify that I stored the answer in this variable because I didn't think it could be related... Morality: always specify everything !
I'm using Vuex to handle my application state.
I need to make an Ajax Get request to a rest api and then show some objects list.
I'm dispatching an action that loads this data from the server but then I don't know how to handle it on the component.
Now I have this:
//component.js
created(){
this.$store.dispatch("fetch").then(() => {
this.objs = this.$store.state.objs;
})
}
But I don't think that the assignment of the incoming data to the local property is the correct way to handle store data.
Is there a way to handle this better? Maybe using mapState?
Thanks!
There are many ways you can do it, you must experiment and find the one that fits your approach by yourself. This is what I suggest
{ // the store
state: {
something: ''
},
mutations: {
setSomething (state, something) {
// example of modifying before storing
state.something = String(something)
}
},
actions: {
fetchSomething (store) {
return fetch('/api/something')
.then(data => {
store.commit('setSomething', data.something)
return store.state.something
})
})
}
}
}
{ // your component
created () {
this.$store
.dispatch('fetchSomething')
.then(something => {
this.something = something
})
.catch(error => {
// you got an error!
})
}
}
For better explanations: https://vuex.vuejs.org/en/actions.html
Now, if you're handling the error in the action itself, you can simply call the action and use a computed property referencing the value in the store
{
computed: {
something () { // gets updated automatically
return this.$store.state.something
}
},
created () {
this.$store.dispatch('loadSomething')
}
}