socket.io and vue.js fetching data - javascript

I am trying to fetching the data of vue.js using this
fetchData: function () {
socket.emit('getAllSongs')
socket.on('allSongs',function(data) {
this.songs = data
});
}
FetchData is called when the vue app is created
created: function () {
this.fetchData();
}
But when I try to call the variable songs outside socket.on it stills empty.
What could I do?

Try changing you fetchData function to this:
fetchData: function () {
socket.emit('getAllSongs')
var that = this;
socket.on('allSongs',function(data) {
that.songs = data
});
}
The reason is the value this is different in the callback context and is not the component object which you expect it to be.

I think you need to bind this to the end of your function or to use ES6 arrow syntax =>
socket.on('allSongs',function(data) {
that.songs = data
}.bind(this));
socket.on('allSongs',data => {
that.songs = data
});

Related

Call API in another page in nuxtjs

I would like to put my calls to my API in a separate page and not in the template page of my app. So, I create a file "customersAPI.js" and I put this code :
export function findAllCustomers () {
axios.get('http://127.0.0.1:8000/api/customers')
.then((reponse)=>{
console.log(reponse.data['hydra:member'])
return reponse.data['hydra:member']
}).catch(err=>console.log(err))
}
So I try to retrieve my data in my template page and put these data in data but It does not work because of the asynchronous thing of api call and because I don't know how to pass the data...
I do this in my template page :
data() {
return {
customer: [],
}
},
mounted() {
this.getAllCustomers();
},
getAllCustomers() {
this.customer = findAllCustomers();
}
I know it is not the good way to do this but I don't know how to do... So I need clarification about that. And, every time I go into the documentation, there are no examples with an API call outside of the part where there is the page template. Is it a good practice to want to put the api call apart? And in general calls to functions so that the code is not too long?
Thanks for help
In your case I advise you to try add async in mounted or in func.
async mounted() {
this.customers = await this.findAllCustomers();
},
------
methods: {
async getAllCustomers(){
this.customer = await findAllCustomers();
}
}
But better practice to fetch information from store:
COMPONENT
<script>
import {mapActions} from 'vuex'
export default {
data() {
return {
customer: [],
}
},
mounted() {
this.customer = this.fetchAll();//better to get via getters
},
methods() {
...mapActions('customers', ['fetchAll']),
//OR
// fetchAllCustomers(){
// this.$store.dispath('customers/fetchAll')
// }
}
}
</script>
STORE
// async action that put all customers in store
const fetchAll = async ({ commit }) => {
commit(types.SET_ERROR, '')
commit(types.TOGGLE_LOADING, true)
try {
const { data} = await customerAPI.findAll(namespace)
commit(types.SET_ALLIDS, data['hydra:member'])
commit(types.TOGGLE_LOADING, false)
return data['hydra:member']
} catch (error) {
commit(types.TOGGLE_LOADING, false)
commit(types.SET_ERROR, error)
}
},
API
// func that receive promise
export function findAll () {
return axios.get('http://127.0.0.1:8000/api/customers')
}
Please read about vuex
https://vuex.vuejs.org/guide/actions.html

How can i pass data from window method to the data function in a Vuejs app

I need to pass data from window method to the data function of a vuejs component
here is my window function
window.authenticate = function(pid, receiptKey) {
console.log("Authentication");
console.log(this)
localStorage.setItem("pid",pid)
alert("pid="+pid+"receipt="+receiptKey)
window.pid=pid
window.receiptKey = receiptKey
}
Data function:
data: () => ({
pid: 0,
receipt: 0
}),
trying to set the Pid and receipt key mounted, where am I wrong ?
mounted: function (){
this.pid = window.pid
alert(this.pid)
this.receipt = window.receiptKey
}
I did some research and found that the created lifecycle hook can be used for this purpose as below
1) we need to bind the window method with component method, window.authenticate to loginCall in the below example, and it all works.
created: function () {
// `this` points to the vm instance
console.log('a is: ' + this.a)
// window.somefunc = this.greet.bind(this);
window.authenticate = this.loginCall.bind(this)
},
methods: {
loginCall: function (pid, receipt) {
}

Vuejs ajax call not mapping changes to underlying html table

I am making simple ajax call with vuejs and axios:
var app1 = new Vue({
el: '#app1',
data: {
test: []
},
methods: {
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
}
}
});
Why is this working:
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(response => this.test = response.data.listBACAET);
}
But this is not working, changes are not mapped into table (this.test is undefined):
setAJAX: function () {
axios.get('/Departments/GetDepartments/').then(function(response){this.test = response.data.listBACAET});
}
This is because of the way arrow functions work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this
When using an arrow function, this is implicitly bound to this of the enclosing scope, which is, in your case, the vue instance on which the method is called.
So you're setting the data of your view model, which works.
When using a std. function, there is no this in the scope, hence the error. To use a std. function, you need to define a closure for your view model like this:
setAJAX: function () {
let vm = this
axios.get('...').then( function(response) {
vm.test = response.data.listBACAET
});
}

Calling 'this' inside of firebase once function

So I am creating a Vuejs application and I am trying to fetch firebase data on component mount. That is working, but I try to write the value into a vuejs data property. For this I would only call this.property = snapshot.val(); inside the firebase function (see code below) but that is not working: this is undefined
So my code just is:
export default {
data() {
return {
imageList: "No images!"
}
},
mounted() {
if (!firebase.apps.length) {
// Initialize Firebase
var config = {
...
};
firebase.initializeApp(config);
var database = firebase.database();
var ref = database.ref("images").orderByChild("date");
firebase.database().ref("images/").once('value').then(function(snapshot) {
this.imageList= snapshot.val();
});
}
}
}
I tried calling this.imageList= snapshot.val(); outside of the function with a variable to store the value, and 'this' wasn't undefined anymore, but the data wasn't there because the request hasn't finished yet.
So basically I want to get the snapshot.val(); into this.imageList!
Thanks in advance.
You can use es6 arrow function syntax to solve the issue.
firebase.database().ref("images/").once('value').then((snapshot) => {
this.imageList= snapshot.val();
});
or bind this to the context of the function.
var that = this;
Use an arrow function, a closure, or bind.
firebase.database().ref("images/").once('value').then(snapshot => {
this.imageList= snapshot.val();
});
See How to access the correct this inside a callback.
You can use bind as well.
firebase.database().ref('images/').once('value').then(function(snapshot) {
this.imageList = snapshot.val()
}.bind(this))

Javascript (react native): how to avoid that = this?

I'd like to avoid let that = this; because it seems to be a dirty solution. Is it e.g. possible to use .bind(this) anyhow?
My current code:
// ...
componentDidMount() {
let that = this; // <- how to avoid this line?
this.props.myService.listensTo('action', (data) => {
that.handleData(data);
});
}
handleData(data) {
// handle data
}
// ...
Thanks in advance!
Basically arrow functions will help with this and since React-Native doesnt have to deal with browser compatibility you can define you're functions like this:
handleData = (data) => {
this.setState({ data });
}
You won't ever have to .bind or that=this if you use this.
this is already bound because of the arrow function you've used.
// ...
componentDidMount() {
this.props.myService.listensTo(
'action',
(data) => this.handleData(data)
);
}
handleData(data) {
// handle data
}
// ...

Categories

Resources