How to send data from one Electron window to another with ipcRenderer using vuejs? - vuejs2

I have in one component this:
openNewWindow() {
let child = new BrowserWindow({
modal: true,
show: false,
});
child.loadURL('http://localhost:9080/#/call/' + this.chatEntityId + '?devices=' + JSON.stringify(data));
child.on('close', function () { child = null; });
child.once('ready-to-show', () => {
child.show();
});
child.webContents.on('did-finish-load', () => {
console.log("done loading");
ipcRenderer.send('chanel', "data");
});
}
And then in child window component:
mounted() {
ipc.on('chanel', (event, message) => {
console.log(message);
console.log(event);
});
}
I tried that .on in created() and beforeCreate() and with this.$nextTick(), withsetTimeout` but nothing works.
I don't want to send some string data but object but as you can see not event simple string "data" works. I am out of ideas.
I can see that this only works in parent component for component where that emit came from if i do this:
send
listen in main process
send back to event.sender
So, question is how to pass any form of data from one window to another?

Ok, after long night, morning after solution.
In some vuejs componenet some action on button click for example
ipcRenderer.send('chanel', someData);
In main process
ipcMain.on('chanel', (event, arg) => {
let child = new BrowserWindow()
// other stuff here
child.loadURL(arg.url)
child.on('show', () => {
console.log("done loading");
child.webContents.send('data', arg);
});
})
In vuejs component for other route arg.url
mounted() {
ipc.on('chanel', (event, message) => {
console.log(message);
console.log(event);
});
}

Related

Toast function not showing

submit() {
if(this.submitvalidtion()) {
this.loading = true;
axios.post('/api/vaccine/create_baby_info', this.form).then(res => res.data).then(res => {
//console.log(JSON.stringify(res));
this.$bvToast.toast(res.data.message,{ variant:'success', noCloseButton: true,solid:true})
this.loading = false;
})
.catch((error) => {
let error_msg = error.res.data.message;
this.$bvToast.toast(error_msg,{ variant:'danger', noCloseButton: true, solid:true})
this.loading = false;
});
}
},
Hi i am new to vue js, and can someone help me with this.
After i clicked the submit button , the 'toast' function not showing up
Call function inside methods in this way:
submit: function () {
// condition code add here
}
For calling submit function call in this way
vm.submit()

Vuejs created and mounted doesn't work properly even if at the same level than methods

I'm experiencing a strange behaviour with created() and mounted() in Vue.js. I need to set 2 lists in created() - so it means those 2 lists will help me to create a third list which is a merge.
Here is the code :
// return data
created () {
this.retrieveSellOffers();
this.getAllProducts();
},
mounted () {
this.mergeSellOffersProducts();
},
methods: {
retrieveSellOffers() {
this.sellerId = localStorage.sellerId;
SellOfferServices.getAllBySellerId(this.sellerId)
.then((response) => {
this.sellOffers = response.data;
console.log("this.sellOffers");
console.log(this.sellOffers);
})
.catch((e) => {
console.log(e);
});
},
getAllProducts() {
ProductServices.getAll()
.then((response) => {
this.products = response.data;
console.log("this.products");
console.log(this.products);
})
.catch((e) => {
console.log(e);
});
},
mergeSellOffersProducts () {
console.log(this.products) // print empty array
console.log(this.sellOffers) // print empty array
for (var i = 0; i < this.sellOffers.length; i++) {
if (this.sellOffers[i].productId === this.products[i]._id) {
this.arr3.push({id: this.sellOffers[i]._id, price: this.sellOffers[i].price, description: this.products[i].description});
}
}
this.arr3 = this.sellOffers;
},
}
//end of code
So my problem is when I enter in mergeSellOffersProducts(), my 2 lists are empty arrays :/
EDIT :
This way worked for me :
async mounted() {
await this.retrieveSellOffers();
await this.getAllProducts();
this.mergeSellOffersProducts();
},
methods: {
async retrieveSellOffers() {
this.sellerId = localStorage.sellerId;
this.sellOffers = (await axios.get('link/api/selloffer/seller/', { params: { sellerId: this.sellerId } })).data;
},
async getAllProducts() {
this.products = (await axios.get('link/api/product')).data;
},
}
I think the reason is: Vue does not wait for the promises to resolve before continuing with the component lifecycle.
Your functions retrieveSellOffers() and getAllProducts() contain Promise so maybe you have to await them in the created() hook:
async created: {
await this.retrieveSellOffers();
await this.getAllProducts();
}
So I tried to async my 2 methods :
async retrieveSellOffers() {
this.sellerId = localStorage.sellerId;
this.sellOffers = (await axios.get('linkhidden/api/selloffer/', { params: { sellerId: '615b1575fde0190ad80c3410' } })).data;
console.log("this.sellOffers")
console.log(this.sellOffers)
},
async getAllProducts() {
this.products = (await axios.get('linkhidden/api/product')).data;
console.log("this.products")
console.log(this.products)
},
mergeSellOffersProducts () {
console.log("here")
console.log(this.sellOffers)
console.log(this.products)
this.arr3 = this.sellOffers;
},
My data are well retrieved, but yet when I enter in created, the two lists are empty...
You are calling a bunch of asynchronous methods and don't properly wait for them to finish, that's why your data is not set in mounted. Since Vue does not await its lifecycle hooks, you have to deal with the synchronization yourself.
One Vue-ish way to fix it be to replace your method mergeSellOffersProducts with a computed prop (eg mergedSellOffersProducts). Instead of generating arr3 it would simply return the merged array. It will be automatically updated when products or sellOffers is changed. You would simply use mergedSellOffersProducts in your template, instead of your current arr3.
If you only want to update the merged list when both API calls have completed, you can either manually sync them with Promise.all, or you could handle this case in the computed prop and return [] if either of the arrays is not set yet.
When you're trying to merge the 2 lists, they aren't filled up yet. You need to await the calls.
async created () {
await this.retrieveSellOffers();
await this.getAllProducts();
},
async mounted () {
await this.mergeSellOffersProducts();
},

AddEventListener DOM event Jest testing

I have one Users vue component and I am trying to test mounted() with addEventListener.
Users.vue
=========
mounted(){
let viewPort = document.getElementById("Users-list"); ----> Here I am getting null for addEventListener.
viewPort!.addEventListener("scroll", (e: any) => {
let result =
e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight ===
0;
if (result) {
this.test = this.Offset + this.Limit;
this.response = this.GetDetails();
}
});
}
I have written spec for Users component and trying to test mounted() method with addEventListener.
But I am getting an error message cannot read property addEventListener of null.
Users.spec.ts
=============
describe('Users TestSuite', async () => {
let userWrapper: any;
let userObj: any;
beforeEach(() => {
userWrapper = shallowMount(Users, {
// attachTo: document.getElementById('Users-list'),
localVue,
i18n,
router
})
userObj = userWrapper.findComponent(Users).vm;
const mockAddeventListener = jest.fn().mockImplementation((event, fn) => {
fn();
})
document.getElementById = jest.fn().mockReturnValue({
scrollTop: 100,
clientHeight: 200,
scrollHeight: 500,
addEventListener: mockAddeventListener
})
expect(mockAddeventListener).toBeCalledWith('scroll', expect.anything());
});
it('should render Users page', () => {
expect(userObj).toBeTruthy();
});
I think the problem here might be u are creating the mock function after u are creating the component. Mounted method will be called when the wrapper is created so try to move the mock implementation above the wrapper statement.
Another sure way in which to make it work is before u create the wrapper set the body of the document like document.body.innerHTML = <div id="users-list"></div>. This will definitely work.
For both the above solutions make sure that they are above the wrapper statement.

vue.js1 event not emitting if 4 listerns are registered

I have a very weird issue. I might be doing something very silly here but not aware of it.
I am using vue.js 1. I have a component which is a bootstrap modal that emits 4 custom events. For each of these, I have a listener registered on the parent. The very strange issue is, whenever i am registering the 4th listener, the event that this 4th listener is registered for is not emitting!
// on parent component template...
<fbu-create-maker-commission-modal
v-ref:new-commission-modal
modal-id="addSpCommissionModal"
:show-modal="showCreationModal"
v-on:hiding-modal="onHidingModal"
v-on:sp-commission-created="onCreatingNewSpCommission"
v-on:sp-commission-updated="onUpdatingSpecialCommission"
v-on:sp-commission-remove="onDeletingSpecialCommission"
:modal-template-data="templateData"
:mode="modalLaunchMode"
:object-to-edit="toEditObject"
></fbu-create-maker-commission-modal>
// child component code where the events are emitted from
editCommission() {
let config = Object.assign({}, this.modalTemplateData.httpConfig.updateSpecialCommission, { body: this.form.formData })
this.$http(config).then(response => {
console.log(response);
if(this.isVueResourceResponseValid(response)) {
this.$emit('sp-commission-updated', response.body.data.updatedCommission);
this.handleModalClose();
}
}).catch(errorResponse => {
console.log(errorResponse);
if(errorResponse.status == 422) {
for(errorKey in errorResponse.body) {
this.$set(`form.errors.${errorKey}`, errorResponse.body[errorKey]);
}
}
});
},
deleteCommission() {
let config = Object.assign({}, this.modalTemplateData.httpConfig.deleteSpecialCommission, { body: this.form.formData })
// console.log(config);
this.$http(config).then(response => {
// console.log(response);
if(this.isVueResourceResponseValid(response)) {
console.log('here');
this.$emit('sp-commission-remove', response.body.data.deletedSpecialCommission);
this.handleModalClose();
}
}).catch(errorResponse => {
});
},
createCommission() {
let config = Object.assign({}, this.modalTemplateData.httpConfig.createSpecialCommission, { body: this.form.formData })
this.$http(config).then(response => {
if(this.isVueResourceResponseValid(response)) {
this.$emit('sp-commission-created', response.body.data.newCommission);
this.handleModalClose();
}
}).catch(errorResponse => {
if(errorResponse.status == 422) {
for(errorKey in errorResponse.body) {
this.$set(`form.errors.${errorKey}`, errorResponse.body[errorKey]);
}
}
});
},
It's the sp-commission-remove event that is not being emitted if i register a listner for this on the parent, like this - v-on:sp-commission-remove="onDeletingSpecialCommission"
if i remove this listener, or even change any character of the custome event name, event emitts fine!!
Are there any limit on how many listeners/events can be emitted in Vue1?
It's driving me nuts. Can someone guide me to the right direction pls?

Component not unmounting when user navigates to new screen

new to React Native here.
I have a simple component/screen with this code:
useEffect(() => {
console.log("OPENING LOGIN");
AppState.addEventListener("change", testFunction);
return (() => {
console.log("Removing HELLO LISTENER");
AppState.removeEventListener("change", testFunction);
});
}, []);
const testFunction = () => {
console.log("APPSTATE CHANGE FUNCTION RUNNING");
};
const changeScreen = () => {
return props.navigation.navigate("MainView", {});
};
This starts a eventListener when the component is mounted. When the component is unmounted, I log something else out, and would like to remove the same listener.
However, when the changeScreen function is fired, which navigates the user to a whole new component/screen, I do not receive the "Removing HELLO LISTENER" log, and the listener still fires.
My question is:
Why is this component not unmounted when naivagting to a new Screen?
Thank you for your time!