vue js Cannot read property 'data' of undefined* - javascript

I am new to vue js.
this.comments.unshift(response.body.data); is not working.
I did not use json() like this.comments.unshift(response.json().data); and this.comments = response.json().data; because using json() does not show any comments. I just searched and someone mentioned to use 'body' instead of json().
Saving a comment in database is working. Only problem is showing a new comment is not working without refresh page.
These are error messages
[Vue warn]: Error in render function: "TypeError: Cannot read property 'data' of undefined"
TypeError: Cannot read property 'data' of undefined
Thank you very much.
<script>
export default {
data () {
return {
comments: [],
body: null
}
},
props: {
postid: null
},
methods: {
getComments () {
this.$http.get('/blog/' + this.postid+ '/comments').then((response) => {
this.comments = response.body.data;
});
},
createComment () {
this.$http.post('/blog/' + this.postid+ '/comments', {
body: this.body
}).then((response) => {
// console.log(this.body);
this.comments.unshift(response.body.data);
this.body = null;
});
}
},
mounted () {
this.getComments();
} }
</script>

Related

Reach content of variable in another method

I'm trying to reach the content of matchData from a Vue method. I'm able to console.log(this.matchData), but not able to get its content.
When I console.log(this.matchData[0].matchScores[0]) under method readMatchPlayerScoreIds() I get:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'matchScores' of undefined"
export default {
data() {
return {
matchData: [],
};
},
methods: {
readMatches() {
db.collection("matches")
.get()
.then((queryMatchSnapshot) => {
queryMatchSnapshot.forEach((doc) => {
this.matchData = [];
this.matchData.push({
awayscore: doc.data().awayscore,
homeScore: doc.data().homeScore,
matchScores: doc.data().matchscores,
})
});
console.log(this.matchData[0].matchScores[0])
});
},
readMatchPlayerScoreIds() {
console.log(this.matchData[0].matchScores[0])
}
},
mounted() {
this.readMatches();
this.readMatchPlayerScoreIds();
},
};
Since you are fetching data from the db asynchronously, the data will be empty until the db call was completed. You should read the data after the Promise has been resolved. (reformulating my comment as answer).
One way to do it, could be to return the Promise from readMatches:
export default {
data() {
return {
matchData: [],
};
},
methods: {
readMatches() {
return db.collection("matches")
.get()
.then((queryMatchSnapshot) => {
queryMatchSnapshot.forEach((doc) => {
// this.matchData = []; // <= why would you reset it in each loop?
this.matchData.push({
awayscore: doc.data().awayscore,
homeScore: doc.data().homeScore,
matchScores: doc.data().matchscores,
})
});
console.log(this.matchData[0].matchScores[0])
});
},
readMatchPlayerScoreIds() {
console.log(this.matchData[0].matchScores[0])
}
},
mounted() {
this.readMatches()
.then(() => this.readMatchPlayerScoreIds());
},
};
But it depends on what you want do to in readMatchPlayerScoreIds method body.
Also, be aware not to reset matchData in the forEach loop.

'Vue.js' Errors in communicating between parent and children

i have application that calls several requests and displays that data. Everything is working, but I getting some errors that I can't figure out where is the problem..
So I have two components:
--App :Parent
---Events :Children
In App.vue calling children component:
<Events :events="gameInfo" :results="results" #startNewGame="startNewGame" />
Giving as a props "gameInfo", "results" and listening for "startNewGame" event.
When application loads first time in App.vue i'm calling function:
// Get Next Game
getNextGame() {
this.gameInfo = [];
RouletteApi.getNextGame().then(response => {
this.gameInfo.push({ response });
});
}
That children component receives and displays data.
In children component:
<script>
export default {
name: "Events",
props: ["events", "results"],
data() {
return {
GameStartTime: null,
GameId: null,
GameUUID: null
};
},
watch: {
events: function(newVal, oldVal) {
this.GameStartTime = newVal[0]["response"].fakeStartDelta--;
this.GameId = newVal[0]["response"].id;
this.GameUUID = newVal[0]["response"].uuid;
}
},
created() {
setInterval(() => {
if (this.GameStartTime > 0) {
this.GameStartTime = this.events[0]["response"].fakeStartDelta--;
} else {
this.$emit("startNewGame", this.GameUUID); -- call to parent function
}
}, 1000);
}
};
</script>
I watching, getting the data and setting timer, to execute "startNewGame" function from parent, that will make another api call and give children new data.
After timer expires I'm calling "startNewGame" function from parent:
startNewGame(uuid) {
this.startSpinning();
RouletteApi.startNewGame(uuid).then(response => {
if (response.result == null) {
setTimeout(function() {
startNewGame(uuid);
}, 1000);
} else {
this.results.push({ response });
this.gameInfo = []; -- resetting that previous dat
this.getNextGame(); -- call to first function in example
}
});
That checks if response is null then setting timeout and calling that function until response will be not null. If response came not null than I pushing to children result, resetting that gameInfo array and calling again getNextGame() function that will call request and set new value for timer in children component.
RouletteApi.js:
import axios from 'axios'
export default {
getLayout() {
return axios.get('/configuration')
.then(response => {
return response.data
})
},
getStats() {
return axios.get('/stats?limit=200')
.then(response => {
return response.data
})
},
getNextGame() {
return axios.get('/nextGame')
.then(response => {
return response.data
})
},
startNewGame(uuid) {
return axios.get('/game/' + uuid)
.then(response => {
return response.data
})
}
}
Errors:
Error in callback for watcher "events": "TypeError: Cannot read property 'response' of undefined"
TypeError: Cannot read property 'response' of undefined
at VueComponent.events (Events.vue?5cf3:30)
Uncaught ReferenceError: startNewGame is not defined
First two errors i'm getting from children component in "watch" part.
Last one when calling function in setInterval in parent component.
It looks like the watcher is running before the api call finished. Console log the new value to see what your get. Try to check if the newVal is not null or an empty array and then set the values.

TypeError: Cannot read property 'push' of undefined [VueJs]

I am trying to add an object to an array but it is not working with me, the program can't read the property push
I defined an array in <script>:
Data: function() {
return {
Projects: [
{
name: '',
id: 0,
subscribers: 0,
products: {name:'',color:''},
}
],
}
And in the function:
GetAllWorkspaces: function(){
var app = this;
const instance = axios.create({
timeout: 1000,
headers: {
........
}
});
instance.get("XXXXXXX")
.then( function(response) {
console.log(response);
Object.keys(response.data.result).forEach( function (product) {
var subscribersCounter = 0;
let example = {
name: response.data.result[product].name,
id: response.data.result[product].id,
subscribers: response.data.result[product].subscribers,
products: response.data.result[product].products,
};
let uploadedExample = {
name: '',
id: '',
subscribers: '',
products: {name:'',color:''},
};
uploadedExample.name = example.name;
uploadedExample.id = example.id;
if ( example.subscribers ) {
Object.keys(example.subscribers).forEach(function (key) {
subscribersCounter++;
});
}
uploadedExample.subscribers = subscribersCounter;
if ( example.products ) {
Object.keys(example.products).forEach(function (Pkeys) {
uploadedExample.products.name = Pkeys;
Object.keys(example.products[Pkeys]).forEach(function (key) {
if (key == 'color') {
uploadedExample.products.color = example.products[Pkeys][key];
}
});
});
}
//add the new workspace to the list of workspaces.
app.Projects.push(uploadedExample);
});
})
.catch(function(error) {
console.log(error);
});
My problem is with this line
app.Projects.push(uploadedExample);
where when I try to push an object into the array, the error message is shown:
TypeError: Cannot read property 'push' of undefined
As the error says, the problem is that app.Projects is undefined. This happens because 'this' refers to the function scope inside GetAllWorkspaces and not to the component scope (you can try it by console.logging 'this' - anyway- it is a good practice under all circumstances because 'this' can change from context to context). If you want to keep the component scope inside the method, you should use an arrow function like this:
GetAllWorkspaces: () => {
// do all your stuff
}

Vue js error push with method sendMessage

I have method:
props: ['convId'],
data() {
return {
messages: [],
newMessage: ''
};
},
methods: {
sendMessage() {
axios.post('/sendMessage/' + this.convId, { message: this.newMessage })
.then(response => this.messages.push(response.data.data));
this.messages.push(newMessage);
this.newMessage = '';
console.log(this.messages.id); //TypeError: Cannot read property 'id' of undefined
}
},
When I try get updated this.messages. I get undifined properties of this object. Why?
In request I return object:
{"body":"test","user_id":1,"type":"text","conversation_id":1,"updated_at":"2018-06-04 13:15:27","created_at":"2018-06-04 13:15:27","id":16,"conversation":{"id":1,"private":1,"data":null,"created_at":"2018-06-01 12:54:33","updated_at":"2018-06-04 13:15:27","users":[{"id":1,"name":"Axer","email":"test#gmail.com","created_at":"2018-06-01 12:35:37","updated_at":"2018-06-01 12:35:37","pivot":{"conversation_id":1,"user_id":1,"created_at":"2018-06-01 12:54:33","updated_at":"2018-06-01 12:54:33"}},{"id":2,"name":"Testumus","email":"teadasdasd#gmail.com","created_at":"2018-06-01 12:46:30","updated_at":"2018-06-01 12:46:30","pivot":{"conversation_id":1,"user_id":2,"created_at":"2018-06-01 12:54:33","updated_at":"2018-06-01 12:54:33"}}]}}
How I can fix this?
You haven't specified newMessage variable. Maybe you wanted to insert this.newMessage.
If you are trying to get the result thats been insert maybe you can return the database data into the response and then push in message , that way you'll be able to get id and other column which you are using to log it out on console.
axios.post('/sendMessage/' + this.convId, { message: this.newMessage })
.then((response) {
this.messages.push(response.data.data) // Fetched message from server
this.newMessage = '';
console.log(this.messages.id);
})
props: ['convId'],
data() {
return {
messages: [],
newMessage: ''
};
},
methods: {
sendMessage() {
axios.post('/sendMessage/' + this.convId, { message: this.newMessage })
.then((response) {
this.messages.push(response.data.data);
this.messages.push(newMessage);
this.newMessage = '';
console.log(this.messages.id);
});
}
},
Try this.

Error in render function: "TypeError: Cannot read property 'indexOf' of undefined"

I've been having troubles with my Vue app that utilizes firebase. I have now gotten the snapshot working correctly and am receiving an object that I convert into an array. Only problem is when I try to filter the object I get I get a "Cannot read property "indexOf" of undefined" The function prints out the array normally and visibly it looks just like what I need, I just can't access it with the includes. Worth mentioning that if I enter a 0,1,2,3 instead of i it doesn't throw the error.
Here is my Vuex exporter with the snapshot of my Firebase
const users = db.ref('users')
users.on('value', function (snapshot) {
store.state.lawyers = Object.values(snapshot.val())
console.log('called')
})
export const store = new Vuex.Store({
state: {
lawyers: '',
selectedLawyerIndex: 1,
selectedCategory: 'Contracts'
},
getters: {
getLawyers: state => {
console.log('state ' + state.lawyers)
return state.lawyers
},
getCurrentLawyer: state => {
return state.lawyers[state.selectedLawyerIndex]
}
}
and the function causing the error:
export default {
data () {
return {
cat: this.$store.getters.getCurrentCategory,
lawyers: this.$store.getters.getLawyers
}
},
components: {
appLawyerWidget: LawyerWidget
},
methods: {
filteredLawyers () {
var arr = []
console.log(this.lawyers)
for (var i = 0; i < this.lawyers.length; i++) {
console.log(JSON.stringify(this.lawyers[i].catarray))
if (JSON.stringify(this.lawyers[i].catarray).indexOf(this.cat) >= 0) {
arr.push(i)
}
}
return arr
}
}
}
any pointers would be greatly appreciated. Thank you!

Categories