I'm trying to remove nodes, type layer, but I'm going crazy... AGHHH!!
I'm using a tree. Using a component of react (rc-tree). There are two types of items: folders and layers.
And I want when delete a folder remove all items inside and when an item will be a layer, different a folder, I could call other method to remove layer from map.
parentis a property that I add when I drop inside a layer on folder.
This is an example of my tree:
And here is my code:
removeNodes = (desiredNode) => {
var parent;
if (desiredNode.parent === undefined && desiredNode.children) {
console.log('1');
} else if (desiredNode.parent !== undefined && desiredNode.children) {
console.log('2', desiredNode);
}
else if (desiredNode.parent !== undefined && !desiredNode.children) {
console.log('3');
parent = getNodeByKey(desiredNode.parent, this.treeData);
parent.children.forEach( (node, index) => {
if (node.key.localeCompare(desiredNode.key) === 0) {
if (parent.children[index].type.localeCompare('folder') !== 0) {
console.log('remove layer with keyName: ', parent.children[index].keyName);
}
parent.children.splice(index, 1);
this.removeTrashCheckedKeys();
}
});
delete parent.children;
}
else {
console.log('4')
var pos = this.treeData.indexOf(desiredNode);
if (this.treeData[pos].type.localeCompare('folder') !== 0) {
console.log('remove layer with keyName: ', this.treeData[pos].keyName);
}
this.treeData.splice(pos, 1);
this.removeTrashCheckedKeys();
}
}
EDIT: This is an idea of a better implementation, but now I have to manage when tree has children, I have to find layers to call a method removeLayerWithName(tree.keyName); to remove layer added in map.
removeNodes = (tree) => {
if (tree.children) {
tree.children.forEach( (node, index) => {
this.removeNodes(node);
});
} else {
var parent = getNodeByKey(tree.parent, this.treeData);
if (parent.children) {
parent.children.forEach( (node, index) => {
if (node.key.localeCompare(tree.key) === 0) {
if (tree.type.localeCompare('folder') !== 0) {
// this.removeLayerWithName(tree.keyName);
console.log('remove layer with keyName: ', tree.keyName)
}
parent.children.splice(index,1);
}
});
if (parent.children.length === 0) {
delete parent.children;
}
} else {
var pos = this.treeData.indexOf(tree);
if (tree.type.localeCompare('folder') !== 0) {
// this.removeLayerWithName(tree.keyName);
console.log('remove layer with keyName: ', tree.keyName);
}
this.treeData.splice(pos, 1);
}
}
this.removeTrashCheckedKeys();
}
I'm making a wild guess here, but does delete parent.children; completely wipe your collection, thus any bindings to it start failing?
You modify that collection, then delete it, seems weird.
SOLUTION:
onDelete = (event, key) => {
if (!window.confirm('Do you want remove it?')) {
return;
} else {
var node = getNodeByKey(key, this.treeData);
this.removeNodes(node);
this.setState({ treeData: this.treeData }, () => {
var parent = getNodeByKey(node.parent, this.treeData);
delete parent.children;
this.props.parentTree(this.treeData);
});
}
this.orderFiles();
event.stopPropagation();
};
removeNodes = (tree) => {
if (tree.children) {
tree.children.forEach( (node, index) => {
if (!node.children) {
if (node.type.localeCompare('folder') !== 0) {
this.removeLayerWithName(node);
var parent = getNodeByKey(node.parent, this.treeData);
parent.children.splice(index,1);
if (parent.children.length > 0) {
this.removeNodes(parent);
}
}
} else {
this.removeNodes(node);
}
});
} else {
var parent = getNodeByKey(tree.parent, this.treeData);
if (parent.children) {
parent.children.forEach( (node, index) => {
if (node.key.localeCompare(tree.key) === 0) {
if (tree.type.localeCompare('folder') !== 0) {
this.removeLayerWithName(tree);
}
parent.children.splice(index,1);
}
});
if (parent.children.length === 0) {
delete parent.children;
}
} else {
var pos = this.treeData.indexOf(tree);
if (tree.type.localeCompare('folder') !== 0) {
this.removeLayerWithName(tree);
}
this.treeData.splice(pos, 1);
}
}
this.removeTrashCheckedKeys();
}
A better implementation:
onDelete = (event, key) => {
if (!window.confirm('¿Estás seguro de eliminarlo?')) {
return;
} else {
var node = getNodeByKey(key, this.treeData);
this.removeNodes(node);
this.setState({ treeData: this.treeData }, () => {
this.props.parentTree(this.treeData);
});
}
this.orderFiles();
event.stopPropagation();
};
removeNodes = (tree) => {
this.layersInTree = [];
this.findLayersInTree(tree);
if (!tree.parent) {
delete tree.children;
var pos = this.treeData.indexOf(tree);
this.treeData.splice(pos, 1);
} else {
var parentNode = getNodeByKey(tree.parent, this.treeData);
delete parentNode.children;
}
}
findLayersInTree = (tree) => {
if (tree.children) {
tree.children.forEach( (node, index) => {
if (!node.children && node.type.localeCompare('folder') !== 0 ) {
this.removeLayerWithName(node);
} else {
this.findLayersInTree(node);
}
});
} else {
if (tree.type.localeCompare('folder') !== 0) {
this.removeLayerWithName(tree);
}
}
}
removeLayerWithName = (nodeLayer) => {
var nodeLayerKeyName = String(nodeLayer.keyName);
this.map.getLayers().forEach( (layer) => {
if (layer !== undefined) {
var layerKeyName = String(layer.getProperties().keyName);
if (layerKeyName.localeCompare(nodeLayerKeyName) === 0) {
this.map.removeLayer(layer);
}
}
});
}
Related
I'm using wschat wordpress plugin. I'm passing link with the conversation id. If there is conversation id we need to get id and activate the particular user conversation.
I'm passing link as https://brookstone220.com/wp-admin/admin.php?page=wschat_chat&cid=3
and the js file will bw:
admin_chat.js:
import {WSChat, formatDate} from './chat';
import { AdminApiConnector } from './admin_api_connector';
import { AdminPusherConnector } from './admin_pusher_connector';
import { EVENTS } from './events';
import { EmojiButton } from '#joeattardi/emoji-button';
import UserMetaInfo from './components/user_meta_info.html'
jQuery(document).ready(function() {
const wrapper = jQuery('.wschat-wrapper');
if (wrapper.length === 0) {
return;
}
const CONVERSATION_TEMPLATE = `
<div class="friend-drawer friend-drawer--onhover" data-conversation-id="{{CONVERSATION_ID}}">
<img class="profile-image" src="https://ui-avatars.com/api/?rounded=true&name=Guest" alt="">
<div class="text">
<h6>{{NAME}}</h6>
<p class="last-message text-truncate">{{LAST_MESSAGE}}</p>
</div>
<span class="time small d-none">{{TIMESTAMP}}</span>
<span class="unread-count badge rounded-pill align-self-center">{{UNREAD_COUNT}}</span>
</div>
<hr>`;
const CHAT_BUBBLE_TEMPLATE = `
<div class="row g-0 w-100 message-item" data-message-id="{{MESSAGE_ID}}">
<div class="col-xs-10 col-md-9 col-lg-6 {{OFFSET}}">
<div class="chat-bubble chat-bubble--{{POS}}">
{{CONTENT}}
</div>
<span class="time">{{TIMESTAMP}}</span>
</div>
</div>`;
const CONVERSATION_TEMPLATE_DEFAULTS = {
'{{CONVERSATION_ID}}': '',
'{{LAST_MESSAGE}}': 'left',
'{{TIMESTAMP}}': '',
'{{NAME}}': '',
};
const BUBBLE_TEMPLATE_DEFAULTS = {
'{{OFFSET}}': '',
'{{POS}}': 'left',
'{{CONTENT}}': '',
'{{TIMESTAMP}}': '',
'{{MESSAGE_ID}}': '',
};
jQuery.ajaxSetup({
data: {
wschat_ajax_nonce: wschat_ajax_obj.nonce
}
});
var chat = new WSChat(jQuery('.wschat-wrapper'), {
connector: wschat_ajax_obj.settings.communication_protocol === 'pusher' ? AdminPusherConnector : AdminApiConnector,
api: {
endpoint: wschat_ajax_obj.ajax_url,
interval: 3000,
wschat_ajax_nonce: wschat_ajax_obj.nonce,
pusher: {
key: wschat_ajax_obj.settings.pusher.app_key,
cluster: wschat_ajax_obj.settings.pusher.cluster,
}
},
alert: {
url: wschat_ajax_obj.settings.alert_tone_url
},
header: {
status_text: wschat_ajax_obj.settings.widget_status === 'online' ? wschat_ajax_obj.settings.header_online_text : wschat_ajax_obj.settings.header_offline_text,
}
});
if (wschat_ajax_obj.settings) {
for(let key in wschat_ajax_obj.settings.colors) {
key && chat.$el.get(0).style.setProperty(key, '#' +wschat_ajax_obj.settings.colors[key]);
}
}
setInterval(() => {
chat.connector.start_conversation();
}, 5000);
const chat_panel = chat.$el.find('.chat-panel');
const conversation_panel = chat.$el.find('.conversation-list');
const chat_panel_header = chat.$el.find('.chat-panel-header');
const chat_tray_box = chat.$el.find('.chat-box-tray');
const message_input = jQuery('#wschat_message_input');
const MESSAGE_INFO = {
min: 0,
max: 0,
};
let PAST_REQUEST_IS_PENDING = false;
let SCROLL_PAUSED = false;
let DISABLE_SCROLL_LOCK = false;
const SCROLL_OFFSET = 100;
const replaceConversation = (conversation) => {
let item = conversation_panel.find('[data-conversation-id='+conversation.id+']');
if (item.length === 0 ) {
return false;
}
item.find('.time').text(conversation.updated_at);
item.find('.last-message').text( conversation.recent_message ? conversation.recent_message.body.text : '');
item.find('.unread-count').text(conversation.unread_count || '');
if (conversation.is_user_online) {
item.addClass('online');
} else {
item.removeClass('online');
}
return true;
};
const sortConversation = () => {
const new_conversation_panel = conversation_panel.clone();
const items = [];
new_conversation_panel.find('[data-conversation-id]').each(function (i, item) {
items.push(item);
});
items.sort((a, b) => {
let timestamp1 = jQuery(a).find('.time').html();
let timestamp2 = jQuery(b).find('.time').html();
return strToDate(timestamp2) - strToDate(timestamp1);
});
new_conversation_panel.html('');
items.forEach((item) => {
new_conversation_panel.append(item);
});
conversation_panel.html(new_conversation_panel.html());
};
const strToDate = (timestamp) => {
let [date1, time1] = timestamp.split(' ');
date1 = date1.split('-');
time1 = time1.split(':');
return parseInt(date1.join('') + time1.join(''));
};
const showNoConversation = () => {
const no_conversation_alert = jQuery('.no-conversation-alert');
conversation_panel.append(no_conversation_alert.removeClass('d-none'));
}
chat.on(EVENTS.WSCHAT_ON_NO_CONVERSATIONS, () => {
showNoConversation();
});
chat.on(EVENTS.WSCHAT_ON_FETCH_CONVERSATIONS, (conversations) => {
conversations.forEach(conversation => {
if (replaceConversation(conversation)) {
return;
}
CONVERSATION_TEMPLATE_DEFAULTS['{{CONVERSATION_ID}}'] = conversation.id;
CONVERSATION_TEMPLATE_DEFAULTS['{{NAME}}'] = conversation.user.meta.name;
CONVERSATION_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(conversation.updated_at);
CONVERSATION_TEMPLATE_DEFAULTS['{{LAST_MESSAGE}}'] = conversation.recent_message ? conversation.recent_message.body.text : '';
CONVERSATION_TEMPLATE_DEFAULTS['{{UNREAD_COUNT}}'] = conversation.unread_count || '';
let row_template = CONVERSATION_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(CONVERSATION_TEMPLATE_DEFAULTS).join('|'), 'g'), match => CONVERSATION_TEMPLATE_DEFAULTS[match]);
row_template = jQuery(row_template);
if (conversation.is_user_online) {
row_template = row_template.addClass('online');
}
if (conversation.user && conversation.user.meta.avatar) {
row_template.find('img.profile-image').attr('src', conversation.user.meta.avatar)
}
conversation_panel.append(row_template);
});
sortConversation();
setTimeout(() => {
let activeItem = conversation_panel.find('.active[data-conversation-id]').length
activeItem === 0 && conversation_panel.find('[data-conversation-id]').eq(0).click();
}, 1000);
});
chat.on(EVENTS.WSCHAT_ON_SET_CONVERSATION, (data) => {
data.user &&
chat_panel_header.find('.username').text(data.user.meta.name);
let info = chat.$el.find('.user-meta-info').html(UserMetaInfo);
chat_panel_header.parent().removeClass('d-none')
info.find('.name').html(data.user.meta.name);
info.find('.browser').html(data.user.meta.browser);
info.find('.os').html(data.user.meta.os);
info.find('.device').html(data.user.meta.device);
info.find('.url').html(data.user.meta.current_url);
message_input.focus();
MESSAGE_INFO.min = 0;
MESSAGE_INFO.max = 0;
DISABLE_SCROLL_LOCK = true;
resizeChat();
setTimeout(() => DISABLE_SCROLL_LOCK = false, 1000);
});
chat.on(EVENTS.WSCHAT_ON_FETCH_MESSAGES, (data) => {
for (let i = 0; i < data.messages.length; i++) {
let row = data.messages[i];
if (row.is_agent === true) {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = 'offset-lg-6 offset-md-3 offset-xs-2';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'right';
} else {
BUBBLE_TEMPLATE_DEFAULTS['{{OFFSET}}'] = '';
BUBBLE_TEMPLATE_DEFAULTS['{{POS}}'] = 'left';
}
BUBBLE_TEMPLATE_DEFAULTS['{{MESSAGE_ID}}'] = row.id;
BUBBLE_TEMPLATE_DEFAULTS['{{CONTENT}}'] = row.body.formatted_content;
BUBBLE_TEMPLATE_DEFAULTS['{{TIMESTAMP}}'] = formatDate(row.created_at);
let row_template = CHAT_BUBBLE_TEMPLATE;
row_template = row_template.replace(new RegExp(Object.keys(BUBBLE_TEMPLATE_DEFAULTS).join('|'), 'g'), match => BUBBLE_TEMPLATE_DEFAULTS[match]);
if (MESSAGE_INFO.min === 0) {
chat_panel.append('<span data-message-id="0"></span>');
}
if (MESSAGE_INFO.min > row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.min+']').before(row_template);
MESSAGE_INFO.min = row.id;
}
if (MESSAGE_INFO.max === 0 || MESSAGE_INFO.max < row.id) {
chat_panel.find('[data-message-id='+MESSAGE_INFO.max+']').after(row_template);
MESSAGE_INFO.max = row.id;
scrollIfNotPaused();
}
if (MESSAGE_INFO.min === 0) {
scrollIfNotPaused();
}
MESSAGE_INFO.min = MESSAGE_INFO.min || row.id;
MESSAGE_INFO.max = MESSAGE_INFO.max || row.id;
}
if (DISABLE_SCROLL_LOCK === true) {
scrollIfNotPaused();
}
});
chat.on(EVENTS.WSCHAT_ON_PONG, (data) => {
let drawer = chat_panel_header.find('.friend-drawer');
let row_template = conversation_panel.find('[data-conversation-id='+data.id+']');
let row_unread_count = row_template.find('.unread-count');
let header_unread_count = chat_panel_header.find('.unread-count');
chat_panel_header.find('.status').text(data.status);
header_unread_count.text(data.unread_count);
row_unread_count.text(data.unread_count || '');
if (data.unread_count) {
header_unread_count.removeClass('d-none');
} else {
header_unread_count.addClass('d-none');
}
if (data.is_online) {
drawer.addClass('online');
row_template.addClass('online');
} else {
drawer.removeClass('online');
row_template.removeClass('online');
}
});
const scrollIfNotPaused = () => {
if (SCROLL_PAUSED === false || DISABLE_SCROLL_LOCK === true) {
chat_panel[0].scrollTop = chat_panel[0].scrollHeight;
}
}
const send_btn = jQuery('#wschat_send_message').on('click', function() {
let msg = message_input.val();
if (msg.trim() === '' && chat.trigger(EVENTS.WSCHAT_CAN_SEND_EMPTY_MESSAGE, false, true) === false) {
return false;
}
chat.sendMessage({
// Type is text by default now, it needs to changed based on the selection content
wschat_ajax_nonce: wschat_ajax_obj.nonce,
type: 'text',
'content[text]': message_input.val()
});
message_input.val('').focus();
});
message_input.keyup(function(e) {
e.key === 'Enter' && send_btn.click();
});
message_input.on('focus', function() {
let unread_count = chat_panel_header.find('.unread-count').text();
if (parseInt(unread_count) > 0) {
chat.trigger(EVENTS.WSCHAT_ON_READ_ALL_MESSAGE);
}
});
chat_panel_header.on('click', '.user-meta-info-toggle', function () {
chat.$el.find('.conversation-wrapper .user-meta-info').toggleClass('d-none');
});
conversation_panel.on('click', '[data-conversation-id]', function() {
chat_panel.html('');
let item = jQuery(this);
let converssation_id = item.data('conversation-id');
conversation_panel.find('[data-conversation-id]').removeClass('active');
item.addClass('active')
chat.connector.join_conversation(converssation_id);
});
chat_panel.on('scroll', function () {
if (DISABLE_SCROLL_LOCK) {
SCROLL_PAUSED = false;
return;
}
if (this.scrollTop < SCROLL_OFFSET) {
if (PAST_REQUEST_IS_PENDING === false) {
PAST_REQUEST_IS_PENDING = true;
chat.connector.get_messages({
after: 0,
before: MESSAGE_INFO.min
});
setTimeout(() => PAST_REQUEST_IS_PENDING = false, 500);
}
}
if (this.offsetHeight + this.scrollTop >= this.scrollHeight - SCROLL_OFFSET) {
SCROLL_PAUSED = false;
} else {
SCROLL_PAUSED = true;
}
});
const resizeChat = () => {
const window_height = jQuery(window).height() - chat.$el.offset().top;
const height = window_height - (
chat_panel_header.height()*2 + chat_tray_box.height()
);
conversation_panel.css({
'min-height': height + 'px'
});
chat_panel.css({
'min-height': height + 'px'
});
};
jQuery(window).resize(() => resizeChat());
resizeChat();
const emojiPicker = document.getElementById('wschat_emoji_picker');
const emoji = new EmojiButton({
style: 'twemoji',
rootElement: emojiPicker.parentElement,
position: 'top'
});
emojiPicker.addEventListener('click', function() {
emoji.togglePicker();
});
emoji.on('emoji', function(selection) {
console.log(selection)
message_input.val(message_input.val() + selection.emoji).focus();
setTimeout(() => message_input.focus(), 500)
});
// Attachment toggler
chat.$el.find('#attachment_picker').click(function (e) {
e.preventDefault();
chat.$el.find('.attachment-list').toggleClass('show d-none');
});
chat.$el.find('.attachment-list').on('click','button', function () {
chat.$el.find('#attachment_picker').click();
});
});
Can someone help me on this? How to get id using this js file and activate the conversation?
Here is what I used for my project to get URL parameters.
var getParameter = function getParameter(param) {
var pageURL = window.location.search.substring(1), // Get current URL substrings
urlVars = pageURL.split('&'), // Split on all "&" for more than one.
parameterName,
i;
for (i = 0; i < urlVars.length; i++) {
// Get the value of the parameter.
parameterName = urlVars[i].split('=');
// Return the value of the parameter if it has the same name as param
if (parameterName[0] === param) {
return typeof parameterName[1] === undefined ? true : decodeURIComponent(parameterName[1]);
}
}
return false;
};
var cID = getParameter('cid');
FilterCriterias: any = []
public productChanged(filterValue: any) {
if(this.FilterCriterias?.length == 0) {
this.FilterCriterias.push({
filtercolumnName: 'productType',
filterValueList: [filterValue.name]
})
} else {
this.FilterCriterias.forEach((elem: any, index: number) => {
if(elem.filtercolumnName == 'productType') {
const idx = elem.filterValueList.indexOf(filterValue.name)
if(idx >= 0) {
elem.filterValueList.splice(idx, 1)
// if (elem.filterValueList?.length == 0 && elem.filtercolumnName == 'productType') {
// const idy = elem.filtercolumnName.indexOf('productType')
// if (idy > 0) {
// this.FilterCriterias.splice(idy, 1)
// }
// }
} else {
elem.filterValueList.push(filterValue.name)
}
} else {
this.FilterCriterias.push({
filtercolumnName: 'productType',
filterValueList: [filterValue.name]
})
}
});
}
this.FilterCriterias.forEach((element: any) => {
if(element.filterValueList.length == 0 && element.filtercolumnName == 'productType') {
console.log(true);
const idy = element.filtercolumnName.indexOf('productType')
console.log(idy);
}
});
// removing the duplicates
var filtered = this.FilterCriterias.reduce((filtered: any, item: any) => {
// console.log(item);
if(!filtered.some((filteredItem: any) => JSON.stringify(filteredItem.filtercolumnName) == JSON.stringify(item.filtercolumnName)))
filtered.push(item)
return filtered
}, [])
console.log('filtered',filtered);
}
public collectionChanged(filterValue: any) {
if(this.FilterCriterias?.length == 0) {
this.FilterCriterias.push({
filtercolumnName: 'collections',
filterValueList: [filterValue.name]
})
} else {
this.FilterCriterias.forEach((elem: any, index: number) => {
if(elem.filtercolumnName == 'collections') {
const idx = elem.filterValueList.indexOf(filterValue.name)
if(idx >= 0) {
elem.filterValueList.splice(idx, 1)
// if(elem.filterValueList?.length == 0) {
// const idy = elem.filtercolumnName.indexOf('collections')
// console.log('collectoinindex',idy);
// if(idy > 0) {
// this.FilterCriterias.splice(idy, 1)
// }
// }
} else {
elem.filterValueList.push(filterValue.name)
}
} else {
this.FilterCriterias.push({
filtercolumnName: 'collections',
filterValueList: [filterValue.name]
})
}
});
}
this.FilterCriterias.forEach((element: any) => {
if(element.filterValueList.length == 0 && element.filtercolumnName == 'collections') {
console.log(true);
const idy = element.filtercolumnName.indexOf('collections')
console.log(idy);
}
});
// removing the duplicates
var filtered = this.FilterCriterias.reduce((filtered: any, item: any) => {
// console.log(item);
if(!filtered.some((filteredItem: any) => JSON.stringify(filteredItem.filtercolumnName) == JSON.stringify(item.filtercolumnName)))
filtered.push(item)
return filtered
}, [])
console.log('filtered',filtered);
}
I am having two functions in which I want to generate a format like below
FilterCriterias: [
{
filtercolumnName:`producttype`,
filterValueList: [`hat`, 'cup']
},
{
filtercolumnName: "collections",
filterValueList: [`modern`, 'pant']
},
]
if the filterValueList.length == 0 means i want to remove the entire object which hold the filerValueList.length == 0.
For Example, if filterValueList of collections is empty means only the producttype needs to be there in the array.
You can achieve that using Array.filter function, like the following:
this.FilterCriterias = this.FilterCriterias.filter(
(item) => !!item.filterValueList.length
);
I am guessing this should do the job if I understood correctly what you want to do. This will loop through all objects of the array, check if their filterValueList array is empty and if so, it will remove them from the array:
let i = 0;
while (i < FilterCriterias.length) {
if(FilterCriterias[i].filterValueList.length == 0) {
FilterCriterias.splice(i, 1);
} else {
i++;
}
}
How to remove sorting from this script part:
getFirstAvailablePeriod() {
const sortedPeriods = this.periods.sort((a: IPeriod, b: IPeriod) => {
if (a.default_price.price === b.default_price.price) {
return 0;
}
return (a.default_price.price > b.default_price.price) ? 1 : -1;
}).filter((period: IPeriod) => !period.locked);
const alreadySelected: IPeriod = sortedPeriods.find((period: IPeriod) => period.id === this.value);
if (alreadySelected) {
return alreadySelected;
}
return sortedPeriods[0];
},
async getPeriods() {
const params: any = {};
if (this.place === 'familyGrave' && this.type === 'multi') {
params.funeral_id = this.item.funeralId;
}
await getPeriods(this.place, this.type, params).then((periods: IPeriod[]) => {
this.periods = periods.sort((period: IPeriod, prev: IPeriod) => {
if (period.sort === prev.sort) {
return 0;
}
return period.sort - prev.sort;
}).filter((period: IPeriod) => {
return !((user()?.role || 'guest') !== 'super-admin' && !this.allowFree && `${period.default_price.price}` === '0');
});
if (!this.value) {
this.$nextTick(() => {
this.handleSelection(this.getFirstAvailablePeriod());
});
}
});
},
This script part reorder Periods from API. Plaese help me to remove rorting Periods from this script. My JS knownleadge is very bad.
Thanks
In getFirstAvailablePeriod instead of
const sortedPeriods = this.periods.sort((a: IPeriod, b: IPeriod) => {
if (a.default_price.price === b.default_price.price) {
return 0;
}
return (a.default_price.price > b.default_price.price) ? 1 : -1;
}).filter((period: IPeriod) => !period.locked);
try this
const sortedPeriods = [...this.periods].sort((a: IPeriod, b: IPeriod) => {
if (a.default_price.price === b.default_price.price) {
return 0;
}
return (a.default_price.price > b.default_price.price) ? 1 : -1;
}).filter((period: IPeriod) => !period.locked);
And to remove all sortings, delete sorting in getPeroids
this.periods = periods.filter((period: IPeriod) => {
return !((user()?.role || 'guest') !== 'super-admin' && !this.allowFree && `${period.default_price.price}` === '0');
});
Remove this part
.sort((period: IPeriod, prev: IPeriod) => {
if (period.sort === prev.sort) {
return 0;
}
Removed sorting. Give it a try.
getFirstAvailablePeriod() {
const availablePeriods = this.periods.filter((period: IPeriod) => !period.locked);
const alreadySelected: IPeriod = availablePeriods.find((period: IPeriod) => period.id === this.value);
if (alreadySelected) {
return alreadySelected;
}
return availablePeriods[0];
},
async getPeriods() {
const params: any = {};
if (this.place === 'familyGrave' && this.type === 'multi') {
params.funeral_id = this.item.funeralId;
}
await getPeriods(this.place, this.type, params).then((periods: IPeriod[]) => {
this.periods = periods.filter((period: IPeriod) => {
return !((user()?.role || 'guest') !== 'super-admin' && !this.allowFree && `${period.default_price.price}` === '0');
});
if (!this.value) {
this.$nextTick(() => {
this.handleSelection(this.getFirstAvailablePeriod());
});
}
});
},
I am searching for a user, when I find it I want to set it to config state. Now, when I search among children arrays I got a type error saying "Cannot read property 'children' of undefined". Why is it like this? How can I solve it?
I can set the config state if there is no username. Also, if I put a console.log or change something and save, I notice that the page reloads and my searched object is set even if previously it was said that Cannot read property 'children' of undefined.
here the code.
const [config, setConfig] = useState({});
const makeTree = (users) => {
let tree = {children:[]};
for (const person of users) {
if (!person.report) {
tree = { ...person, ...tree };
} else {
if (tree.name === person.report) {
tree.children.push(person);
} else {
tree.children?.forEach(child => {
if (child.name === person.report) {
child.children = [];
child.children.push(person)
}
})
}
}
}
return tree;
};
const searchInChildren = (children, name) => {
for (let i = 0; i<children.length; i++) {
if (children[i]?.name === name) {
setConfig(getConfig(children[i]));
}
else if (children[i] && children[i].children && children[i].children.length > 0) {
searchInChildren(children[i].children, name)
} else {
console.log("not found!")
}
}
};
useEffect(() => {
fetch("http://localhost:4000/schema")
.then((response) => response.json())
.then((data) => {
if (username) {
const treeObj = {...makeTree(data)};
console.log("tree", treeObj);
const regex = new RegExp(username, "gi");
for (let i = 0; i < data.length; i++) {
if (regex.test(data[i].name)) {
if (treeObj.name === data[i].name) {
setConfig(getConfig(treeObj))
} else {
console.log("treeObj.children",treeObj.children, data[i] );
searchInChildren(treeObj.children, data[i].name)
}
}
}
} else {
setConfig(getConfig(makeTree(data)));
}
if(deleteSearch){
console.log("hi",deleteSearch);
setConfig(getConfig(makeTree(data)));
}
});
}, [username, deleteSearch])
;
I'm don't know how to run code if other end
Function showAvailableTable refresh item and add data to vuex $store
I need to run code from ////START to //// END if showAvailableTable() done correctly(axios add data to $store)
how should I do it correctly?
showAvailableTable () {
var obj = this.firstStepData
var nullCount = 0
var self = this
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key] == null) {
nullCount++
}
}
if (nullCount === 0) {
var reservationId = this.firstStepData.restaurant.id
var restaurantSize = this.firstStepData.tableSize.value
var reservationDate = this.firstStepData.reservationDate
var reservationTime = this.firstStepData.reservationTime
axios
.get(self.$store.state.apiUrl + 'reservation/tables/?size=' + restaurantSize + '&restaurant_id=' + reservationId + '&date=' + reservationDate + '&hour=' + reservationTime)
.then(response => {
this.$store.commit('updateRestaurantTableList', response.data)
})
.catch(error => {
console.log(error)
})
this.$store.commit('updateShowTable', true)
}
},
Next function, this function booking table, I'm run this.showAvailableTable() to refresh data in $store
firstStepBook (event, id) {
this.showAvailableTable()
///////////////////START
var isResData = false
this.dataLoading = true
for (var obj in this.restaurantTableList) {
if (this.restaurantTableList[obj].id === id) {
if (this.restaurantTableList[obj].res_tab.length > 0) {
isResData = true
}
break
}
}
if (isResData && !event.currentTarget.classList.contains('isSelected')) {
alert('someone is booking this table, choose another one')
} else {
if (event.currentTarget.classList.contains('isSelected')) {
this.deleteTmpReservation(this.reservationTmp.id)
this.dataLoading = false
} else {
if (this.reservationTmp.id !== undefined) {
this.deleteTmpReservation(this.reservationTmp.id)
this.dataLoading = false
}
var self = this
axios.post(self.$store.state.apiUrl + 'reservation/', {
restaurant_table: id,
clients_number: self.firstStepData.tableSize.value,
reservation_time: self.firstStepData.reservationTime,
reservation_date: self.firstStepData.reservationDate
})
.then(function (response) {
self.showAvailableTable()
self.$store.commit('updateReservationTmp', response.data)
self.dataLoading = false
})
.catch(function (error) {
console.log(error)
})
//this.$store.commit('updateStep', 2)
}
}///////////////////END
},
thank you in advance
This might suit you if the mutation is only called within showAvailableTable()
Ref Vuex subscribe
mounted() {
this.$store.subscribe((mutation, state) => {
if (mutation.type === 'updateRestaurantTableList') {
///////////////////START
...
///////////////////END
}
})
},
methods: {
firstStepBook (event, id) {
// call to updateRestaurantTableList triggers above subscription
this.showAvailableTable()
}
}