VueJS & VUEX: Shortening JS Code - vue.js

I love clean and simple code.
So I like to shorten these lines of javascript so they don't seem so cluttered.
My vuex-mutation code:
editEvent(state) {
if (
state.form.time !== '' &&
state.form.date !== '' &&
state.form.event !== '' &&
state.form.artist !== '' &&
state.form.organizer !== '' &&
state.form.location !== ''
) {
const event = {
time: state.form.time,
date: state.form.date,
event: state.form.event,
artist: state.form.artist,
organizer: state.form.organizer,
location: state.form.location
}
events.child(state.currentEventKey).update(event)
state.form.time = ''
state.form.date = ''
state.form.event = ''
state.form.artist = ''
state.form.organizer = ''
state.form.location = ''
state.currentEventKey = null
state.showForm = false
}
}
and here another one:
populateEventForm(state, payload) {
state.form.time = payload.event.time
state.form.date = payload.event.date
state.form.event = payload.event.event
state.form.artist = payload.event.artist
state.form.organizer = payload.event.organizer
state.form.location = payload.event.location
state.currentEventKey = payload.key
state.showForm = true
}
How can I improve this ?!??!

This is pseudo code for the most part. Somewhere store your common properties.
const props = ["time", "date", "event", "artist", "organizer", "location"]
Then use that in your functions.
function editEvent(state) {
// check to see if every property exists on the state
if (!props.every(p => state.form[p] !== '')) return
// build the event object
const event = props.reduce((acc, p) => acc[p] = state.form[p], {})
// I don't know where "events" comes from-- I left this alone
events.child(state.currentEventKey).update(event)
// clear each property
props.forEach(p => state.form[p] = '')
// clear your misc. props
state.currentEventKey = null
state.showForm = false
}
function populateEventForm(state, payload) {
props.forEach(p => state.form[p] = payload.event[p])
state.currentEventKey = payload.key
state.showForm = true
}
Please be advised, since you posted this as a Vue/Vuex question, you may need to use Vue.set instead of an indexer in cases like the event object being built. It's hard for me to tell from the limited code you posted. In that case it would be something like
const event = props.reduce((acc, p) => {
Vue.set(acc, p, state.form[p])
return acc
}, {})

Related

is there any help about the typeorm orwhere

src/resolver/record/record.query.ts should be able to not pass company id for user that are authUser.isSuperuser
this will not work as expected.
Please do not search for the company in the first place if no company was passed.
with this change it would do the following query:
r.name ILIKE "" OR r.company = null AND (r.secure = false OR r.author = 123)
-> showing all records that match the name search OR where the user has access
public async search(
company: CompanyEntity,
query: string,
start: number = 0,
limit: number = 50,
user: UserEntity = null,
filter: RecordPagerFilterInputModel = null
): Promise<[RecordEntity[], number]> {
const qb = this.recordRepository
.createQueryBuilder('r')
.where('r.meetingRecord IS NULL')
.andWhere('r.name ILIKE ""')
.orWhere('r.company = null')
.andWhere('(r.secure = false OR r.author = 123)')
.setParameters({
query: `%${query}%`,
company: company.id,
secure: false,
author: user ? user.id : -1,
})
.orderBy('r.created', 'DESC')
console.log('qb',qb.getQuery())
if (filter && filter.secure !== undefined) {
qb.andWhere('r.secure = :filterSecure', { filterSecure: filter.secure })
}
if (filter && filter.own !== undefined) {
qb.andWhere(filter.own ? 'r.author = :author' : 'r.author <> :author')
}
if (filter && filter.language !== undefined) {
qb.andWhere('r.language = :filterLanguage', { filterLanguage: filter.language })
}
if (filter && filter.status !== undefined) {
qb.andWhere('r.status IN (:...filterStatus)', { filterStatus: filter.status })
}
qb.skip(start)
qb.take(limit)
return await qb.getManyAndCount()
}
you should use () in all orWhere:
.orWhere(((r.name ILIKE "" OR r.company = null) AND (r.secure = false OR r.author = 123)))

if else in react native

I am new to react native. I Have created a screen where I am using if else in function like this.
constructor(props) {
super(props);
this.state={
phpid = ''
}
}
validateInputs = (event) => {
const data = this.props.route.params.data
const { phpid } = this.state;
if (data.retail_information_data[0] != '') {
phpid == data.retail_information_data[0].id
}else{
phpid == null
}
AsyncStorage.multiGet(["application_id", "created_by"]).then(response => {
console.log(phpid)
fetch('https://njdnfech/Android_API_CI/uploaddata/tffmerchant_retail_details?query=', {
body: JSON.stringify([{phpid : phpid}])
})
.then((returnValue) => returnValue.json())
.then(function(response) {
console.log(response)
return response.json();
}
but I am getting = data.retail_information_data[0] = null or lets say empty
then according to if else my else condition that is 'phpid == null' shuld run
but even 'data.retail_information_data[0] = null' my else condition not running my console kepp saying
'TypeError: undefined is not an object (evaluating 'data.retail_information_data[0].id')'
is any problem in my if else or how to write proper if else
The below should work...
if (data && data?.retail_information_data.length) {
this.setState(phpid: data?.retail_information_data[0]?.id)
}else{
this.setState(phpid: null)
}
Try using ternary operator.
phpid = data.retail_information_data[0] ? data.retail_information_data[0].id : null

VueDraggable of Sortable is not working properly and send the choosed item to the first on init

I'm using Vue.Draggable in my Nuxt project. i used it in some pages and component and every thing is fine. but on one of my pages it gives me a silly problem!! when page is loaded, it send the chosen item to the first!! after that every thing works fine! even if i choose and unchoose without moving, things works fine!!
i tried to check if the choosed went to first of array move it again properly. it worked when the chosen item is the first if array but if i choose others than first, on 2nd try it move another item too!!
so i'm kinda stuck.
here is the code:
btw there are some variables and methods that u cant find them like cmsListItems. they are globally added to my project
template:
<draggable v-model="myItemsArray" #end="onEnd" #choose="onChoose" #unchoose="onUnChoose" v-bind="getOptions()">
<transition-group type="transition" name="sortable_transition">
<categorylistcard v-for="(category, index) in cmsListItems"
listtype="cat"
:key="category.id"
:cat="category"
:index="index"
:showforsub="showForSub"
:parentarr="parentArr"
#addnewsub="addNewCat()"
:sub="true"
:sublvl="true"
:sortable="true"
:btntitle="lang.addsubcat"
/>
</transition-group>
</draggable>
script:
export default {
data(){
return{
oldIndex: '',
newIndex: '',
dragOptions: {
ghostClass: "sortable_ghost",
chosenClass: "sortable_chosen",
handle: ".sortable_handle",
disabled: false
},
isMoved: false,
myItemsArray: [],
originalItemsArray: [],
choosedItem: null
}
},
methods:{
// ***** Reorder By Sorting *****\\
this.isMoved = true
this.oldIndex = event.oldIndex
this.newIndex = event.newIndex
console.log(this.myItemsArray[this.oldIndex])
console.log(this.myItemsArray[this.newIndex])
if(this.oldIndex !== this.newIndex){
this.dragOptions.disabled = true
let response = await this.axiosGet(`category/reorder/${this.originalItemsArray[this.oldIndex].id}/${this.originalItemsArray[this.newIndex].id}`)
if(this.resOk(response.status)){
this.noty(ALERT_TYPE[1], 'ok')
this.originalItemsArray = this.myItemsArray
this.isMoved = false
this.dragOptions.disabled = false
this.addClassToMovedItems(this.oldIndex)
this.addClassToMovedItems(this.newIndex)
this.setCmsListItems(this.myItemsArray)
// this part is my defected solution
setTimeout(() => {
if(this.myItemsArray[this.oldIndex].id === this.choosedItem.id || this.myItemsArray[0].id === this.choosedItem.id){
let arrayOfItems = [...this.originalItemsArray]
arrayOfItems.shift()
arrayOfItems.splice(this.newIndex,0,this.choosedItem)
this.setCmsListItems(arrayOfItems)
this.myItemsArray = [...this.cmsListItems]
}
}, 50);
// --------------------
}else{
this.isMoved = false
this.myItemsArray = this.originalItemsArray
this.dragOptions.disabled = false
this.addClassToMovedItems(this.oldIndex)
this.addClassToMovedItems(this.newIndex)
}
}else{
this.isMoved = false
this.myItemsArray = this.originalItemsArray
this.dragOptions.disabled = false
this.addClassToMovedItems(this.oldIndex)
this.addClassToMovedItems(this.newIndex)
}
},
addClassToMovedItems(index){
if((index == this.oldIndex || index == this.newIndex) && this.isMoved == true){
return 'sortable_moved'
}else{
return ''
}
}
},
async fetch(){
this.btnLoading = true
let response = await this.axiosGet(`categories/admin/0/1`)
if(this.resOk(response.status)){
if(this.notEmpty(response.data)){
this.setCmsListItems(response.data.items)
this.myItemsArray = [...this.cmsListItems]
this.originalItemsArray = [...this.cmsListItems]
}
this.btnLoading = false
}
},
}
I kinda hacked through it, so i don't recommend it!!
I got the chosen item with #choose and in my #end checked if first index of my array is the chosen item, unshift array and add the chosen to newIndex with splice() like bellow:
setTimeout(() => {
if(this.myItemsArray[this.oldIndex].id === this.choosedItem.id || this.myItemsArray[0].id === this.choosedItem.id){
let arrayOfItems = [...this.originalItemsArray]
arrayOfItems.shift()
arrayOfItems.splice(this.newIndex,0,this.choosedItem)
this.setCmsListItems(arrayOfItems)
this.myItemsArray = [...this.cmsListItems]
this.choosedItem = null
}
}, 1);

Table, computed property and vuex data

I'm in need of help with computed properties .. it's hard to explain but I'll try ..
I have a table with filter and pagination that I created.
When I pass the data directly from a request the API works,
but when I have to work with data coming from vuex I'm having trouble ...
Because I do not know when the data will be filled in vuex
And then I use the computed property because the moment the vuex is filled it will capture the data ..
However as the function that fills the data is the same one that is executed when I click on the page I crash the process and the page stops working.
Below is the computed property:
list(){
if (this.url_get == '' && this.$store.state.table.list.length > 0){
this.total_data = this.$store.state.table.list.length
this.repos = this.$store.state.table.list
this.getPaginatedItems(1)
}
var filter = this.configs.filter.toString().toLowerCase()
var items = ''
if (filter == ''){
items = this.dados
}else{
items = this.repos
}
const list = this.$lodash.orderBy(items, this.configs.orderBy, this.configs.order)
this.reverse = 1;
if (this.$lodash.isEmpty(filter)) {
return list;
}
var result = this.$lodash.filter(list, repo => {
return repo[this.filter_term].toString().toLowerCase().indexOf(filter) >= 0
})
return result
},
And the function:
getPaginatedItems(data) {
var items = this.repos
var page = data
var per_page = 10
var offset = (page - 1) * per_page
var max_item = offset+per_page
var paginatedItems = this.$lodash.slice(items, offset, max_item)
var obj = {
offset: offset,
current_page: page,
per_page: per_page,
total: items.length,
total_pages: Math.ceil(items.length / per_page),
data: paginatedItems,
last: offset+paginatedItems.length,
max_item: max_item
}
this.pagination = obj
this.dados = this.pagination.data
},
Request who fill the data in vuex
axios
.get(`api/getusuariosgrupo/${id}`)
.then(res => {
if (res.data.dados !== undefined && res.data.dados.length !== 0){
vmThis.isEditing = true
var d = {
list: res.data.dados,
length: res.data.dados.length
}
this.$store.commit('SET_TABLE', d)
}else{
vmThis.isEditing = false
}
vmThis.$bus.$emit('processando',{val: false})
})

Page refresh with onclick event in dojo and I don't want a page refresh

For some reason in IE8 when I run this function after an onclick event it causes a page refresh. I don't wan the page refresh to happen.
var edealsButton = dojo.byId("edeals_button");
var edealEmailInput = dojo.byId("edeals_email");
var edealsSignup = dojo.byId("edeals_signup");
var edealsThankYou = dojo.byId("edeals_thankyou");
var currentValue = dojo.attr(edealEmailInput, 'value');
if (currentValue != '' && currentValue != 'Enter your email') {
var anim = dojox.fx.flip({
node: edealsSignup,
dir: "right",
duration: 300
})
dojo.connect(anim, "onEnd", this, function() {
edealsSignup.style.display = "none";
edealsThankYou.style.display = "block";
})
dojo.connect(anim, "onBegin", this, function() {
var criteria = { "emailAddress": '"' + currentValue + '"' };
alert("currentValue " + currentValue);
var d = essentials.CallWebserviceMethod('AlmondForms.asmx/SignupEdeal', criteria);
d.addCallback(function(response) {
var obj = dojo.fromJson(response);
alert(obj.d);
if (obj != null && obj.d != null) {
//alert(obj.d);
if (obj.d == false)
{
var edealSuccess = dojo.byId("edeals_succes_thankyou");
var edealError = dojo.byId("edeals_error_thankyou");
alert("edealError: " + edealError);
dojo.style(edealSuccess, "display", "none");
dojo.style(edealError, "display", "inline-block");
}
else
{
var edealSuccess = dojo.byId("edeals_succes_thankyou");
var edealError = dojo.byId("edeals_error_thankyou");
dojo.style(edealSuccess, "display","inline-block");
dojo.style(edealError, "display", "none");
}
}
else {
var edealSuccess = dojo.byId("edeals_succes_thankyou");
var edealError = dojo.byId("edeals_error_thankyou");
dojo.style(edealSuccess, "display", "none");
dojo.style(edealError, "display", "inline-block");
}
});
})
anim.play();
edealEmailInput.innerHTML == 'Enter your email';
}
else
{
dojo.attr(edealEmailInput, 'value', 'Enter your email');
dojo.style(edealEmailInput, 'color', '#CC2525');
}
It looks like your "d.addCallback" code might not be disposed of properly. You might want to try placing "dojo.stopEvent()" possibly before the "anim.play();" line and see if this would stop the postback.
From the api.dojotoolkit.org site, the dojo.stopEvent() "prevents propagation and clobbers the default action of the passed event". From the docs.dojocampus.org site, they say that "dojo.stopEvent(event) will prevent both default behavior any any propagation (bubbling) of an event."
Good luck, and hope this helps you out some.