Vue.js - Cannot read property 'push' of undefined [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
I have the following but I get error Cannot read property 'push' of undefined:
var vm = new Vue({
el: '#root',
data: {
posts: [],
newPost: {}
},
createPost: function() {
axios.post("api/posts/create", this.newPost).then(function (response) {
this.posts.push(response.data);
})
}
});
In my network tab in chrome dev tools I can see response.data is clearly an object:
{
"id": 131,
"postContent": "<p>test</p>\n",
}
So why I'm i getting this error?

That's because this context is assigned incorrectly which means that this does not point on the Vue component. To solve this problem, you can use => syntax which simply means a sophisticated way of this self = this outside of the target callback.
createPost: function() {
axios.post("api/posts/create", this.newPost).then((response) => {
this.posts.push(response.data);
})
}

As IzumiSy said, this very common problem when using axios or even setTimeout function. You can use es6 arrow synax, create temporary local variable with vm or bind it to the function.
ES6
createPost: function() {
axios.post("api/posts/create", this.newPost).then((response) => {
this.posts.push(response.data);
})
}
Temporary variable
createPost: function() {
let vm = this;
axios.post("api/posts/create", this.newPost).then(function (response) {
vm.posts.push(response.data);
})
}
Binding
createPost: function() {
axios.post("api/posts/create", this.newPost).then(function (response) {
this.posts.push(response.data);
}.bind(this))
}

Related

cant access data return{} varibles in VueJS

function HeaderreRender() {
HeaderRender = false;
this.$nextTick(() => {
HeaderRender = true;
});
};
export default {
name: 'Home',
components: {
HeaderItem,
},
data: function() {
return {
HeaderRender: true,
};
}
}
this is the code now I want to use v-if="HeaderRender" to re-render the headerItem
but when I call function HeaderreRender()
it is replying to me
Uncaught ReferenceError: HeaderRender is not defined
on the function
any suggestions? on why this happens?
Try to place the HeadereRender() function within the methods object of the component and also, it's this.HeaderRender=true
In simple terms, this method does not know about the HeaderRender variable, thus it is not defined in the scope of the function, written that way

VueJS returns undefined in created function [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
i have started working on a small project using VueJs, i've made a get request using Axios library which returns some data as expected, but I cannot call loadUsers function using this inside mounted
this is my code:
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
axios.get('/Thirdparty/loadUsers').then(function(data){
this.users = data.data;
});
}
},
created(){
let self=this
self.loadUsers();
}
}
as you can see also i've used self variable to call my loadUsers() function, but i'm still getting
this is undefined error
You're referencing this.users within the callback to axios.get().then() in loadUsers(). Due to you're using a standard function and not an arrow function, this is not referring to the Vue instance, i.e. the scope for this is now incorrect. Either use an arrow function or change the reference:
// Do this...
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
axios.get('/Thirdparty/loadUsers').then((data) => { // Using an arrow function.
this.users = data.data;
});
}
},
created(){
let self=this
self.loadUsers();
}
}
// Or this...
export default{
data(){
return {
users : {}
}
},
methods:{
addCustomer(){
//var form = document.querySelector('#add-customer');
var formData = $('#add-customer').serialize();
axios.post('/Thirdparty', formData).then(function(response){
helper.validation(response.data);
//alert(response.data.error);
});
},
loadUsers(){
let self=this; // Adding "self"
axios.get('/Thirdparty/loadUsers').then(function(data){
self.users = data.data; // Referencing "self" instead of "this".
});
}
},
created(){
let self=this
self.loadUsers();
}
}

this.setData is not a function in react [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
I am getting this weird issue in facebook login where I get the response but after getting the response, I am not able to dispatch actions.
Therefore, I wrote a function to do this but I am getting this.setData is not a function.
testAPI() {
window.FB.api('/me' ,function(response) {
console.log("testAPI",response);
if(response){
userProfile = {
access_token:accessToken,
id:response.id,
name:response.name,
provider: "Facebook",
};
console.log("userProfile",userProfile);
this.setData(userProfile);
}
console.log('[FacebookLoginButton] Successful login for: ', response);
});
}
setData = userProfile => {
this.setState(
{
userData: userProfile
},
() => {
console.log("inside setData");
if (userProfile !== undefined) {
console.log("inside callback", userProfile);
this.props.loginUser(this.state.userData);
}
}
);
};
This will help ( https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56 ) [ You need to bind function in order to set context of this ]
You have to use arrow function, or bind function to set correct context of this.
window.FB.api('/me', response => {
// function body
}

javascript create dynamic class by object

Task: I want to create a dynamic class by a given JSON Object in ES6.
After a lot of reading in the MDN web docs and much stackoverflow questions i'm totally confused how to get this work.
JSON Object
{
constructor: {
name: "someName",
},
getter: {
function1: () => "someOutput",
function2: () => false,
}
}
While I tried to solve the problem I figured out how to create dynamic getter methods by using "Proxy" or "defineProperty" but how i should handle the constructor?? :(
I hope someone can help me with a hint or an example.
Thanks in advance
You can add constructor to your class created by Proxy using Proxy's "construct" handler method:
const jsonObj = {
constructor: {
name: "someName",
},
getter: {
function1: () => "someOutput",
function2: () => false,
}
}
function baseClass(obj) {
for(i in obj){
this[i] = obj[i]
}
}
const handler = {
construct(target, args) {
return new target(jsonObj.constructor);
}
};
const NewClass = new Proxy(baseClass, handler);

Access component data in Created or Mounted hook

I'm writing a component for Vue.js and I need to modify data on event. But for some reason, when I access it, it's set as undefined
module.exports = {
data: function() {
return {
visible: true
}
},
mounted: function() {
this.eventHub.$on('minimize', function(window_id) {
console.log(this.visible);
this.visible = !this.visible;
});
},
props: ["windowId"]
}
When the event is called for the first time, data.visible is undefined, for some reason.
Is there anything I'm doing wrong?
Thanks!
Because function (window_id) has it's own scope, you can not access this.
This can be solved by adding self = this.
let self = this
this.eventHub.$on('minimize', function(window_id) {
console.log(self.visible);
self.visible = !self.visible;
});
As Nick Rucci pointed out, you can also use an arrow function, and get rid of self = this.
this.eventHub.$on('minimize', (window_id) => {
console.log(this.visible);
this.visible = !this.visible;
});

Categories