Variable access in ReactJS - reactjs

why i cant access to variable "rows" in method parse?
If i put this.setState({rows: [3,2]}); outside of "parseString it works, but what to do to make it work inside this method?
class App extends React.Component {
constructor(props) {
super(props);
this.state = this.getCleanState();
this.parse = this.parse.bind(this);
}
getCleanState() {
return {
isLoading: true,
columns:[
{ name: 'a:ClientID', title: 'ID kombinace'},
{ name: 'a:Name', title: 'Název kombinace'},
],
defaultColumnWidths: [
{ columnName: 'a:ClientID', width: 160 },
{ columnName: 'a:Name', width: 200 },
],
rows:[],
selection: [],
};
}
parse(XML){
var parseString = require('react-native-xml2js').parseString;
var xml = XML;
parseString(xml, function (err, result) {
console.dir(result);
this.setState({rows: [3,2]});
});
}

because you use an anonymous function that is not binded.
Use arrow function for instance (or explicitly bind)
parse(XML){
var parseString = require('react-native-xml2js').parseString;
var xml = XML;
parseString(xml, (err, result) => {
console.dir(result);
this.setState({rows: [3,2]});
});
}

Related

Gutenberg - Call google map render function in save after DOM has been rendered

I have a bit of a dilemma.
In the save function I need to call a function renderMap that renders a dynamic google map. However I need to call it after the DOM has been rendered. I can't seem to find a solution for this. I realised you can't add a class to the save function with the React lifecycle so I am stopped. It does work for the edit function though. What are the possibilities?
import { __ } from '#wordpress/i18n';
import { registerBlockType } from '#wordpress/blocks';
import { PluginDocumentSettingPanel } from '#wordpress/edit-post';
import { Component } from '#wordpress/element';
const renderMap = function() {
let googleMap = document.getElementById('google-map')
let map
map = new google.maps.Map(googleMap, {
center: { lat: 37.79406, lng: -122.4002 },
zoom: 14,
disableDefaultUI: true,
})
}
registerBlockType( 'splash-blocks/google-maps', {
title: __('Google maps locations', 'google-maps'),
icon: 'megaphone',
category: 'common',
keyword: [
__( 'Display Google maps locations' ),
],
atrributes: {
markers: {
type: 'object'
},
address: {
type: 'string',
default: 'xxxxxxxxx',
},
api_key: {
type: 'string',
default: 'xxxxxxxxx',
}
},
edit: class extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
renderMap()
}
render() {
const { attributes, setAttributes } = this.props
return (
<div id='google-map'>
</div>
)
}
},
save: props => {
const {
className,
attributes: { mapHTML }
} = props;
renderMap()
return (
<div id='google-map'>
</div>
)
}
})

React SyncFusion Resource and grouping crud not binding the data in scheduler

Add event is working(saving to database) but added events are not displaying on scheduler but its working with mocked data . Please let me know if any one know how to bind the data back on scheduler
Please click here to find the attachment image
Please see the above image response getting form api but not binding to scheduler UI
export class GroupEditing extends SampleBase {
constructor() {
super();
this.data = extend([], dataSource.resourceConferenceData, null, true);
this.state = {
customers: [],
technicians: [],
services: [],
groups: [],
};
this.currentEvent;
}
componentDidMount() {
axios
.post('URL', {
userId: '39',
companyId: '38',
dateTime: '2021-03-08 21:43:25',
roleId: 1,
})
.then((res) => {
const data = res.data.content[0];
this.setState({
customers: data.customer,
groups: data.group,
services: data.pestServices,
technicians: data.employee,
});
});
}
addTechnician(args) {
const { technicians } = this.state;
let row = createElement('div', { className: 'custom-field-row' });
let formElement = args.element.querySelector('.e-schedule-form');
const resource = formElement.querySelector('.e-resources-row');
resource.insertBefore(row, resource.firstChild);
let container = createElement('div', {
className: 'custom-field-container',
});
let inputEle = createElement('input', {
className: 'e-field e-input',
attrs: { name: 'employeeId', placeholder: 'Technicians' },
});
container.appendChild(inputEle);
row.appendChild(container);
let dropDownList = new DropDownList({
dataSource: technicians,
fields: { text: 'name', value: 'employeeId' },
value: args.data.Customers,
floatLabelType: 'Always',
placeholder: 'Technicians',
});
dropDownList.appendTo(inputEle);
inputEle.setAttribute('name', 'employeeId');
}
addCustomers(args) {
const { customers } = this.state;
let row = createElement('div', { className: 'custom-field-row' });
let formElement = args.element.querySelector('.e-schedule-form');
formElement.firstChild.insertBefore(row, formElement.firstChild.firstChild);
let container = createElement('div', {
className: 'custom-field-container',
});
let inputEle = createElement('input', {
className: 'e-field e-input',
attrs: { name: 'customerId', placeholder: 'Customers' },
});
container.appendChild(inputEle);
row.appendChild(container);
let dropDownList = new DropDownList({
dataSource: customers,
fields: { text: 'customerName', value: 'customerId' },
value: args.data.Customers,
floatLabelType: 'Always',
placeholder: 'Customers',
});
dropDownList.appendTo(inputEle);
inputEle.setAttribute('name', 'customerId');
}
onPopupOpen(args) {
if (args.type === 'Editor') {
if (!args.element.querySelector('.custom-field-row')) {
debugger;
this.addCustomers(args);
this.addTechnician(args);
}
}
}
render() {
const { services, groups, loading } = this.state;
return (
<div className='schedule-control-section'>
<div className='col-lg-12 control-section'>
<div className='control-wrapper'>
<ScheduleComponent
rowAutoHeight={true}
// popupOpen={this.onPopupOpen.bind(this)}
cssClass='group-editing'
width='100%'
height='650px'
selectedDate={new Date()}
// currentView='Day'
eventSettings={{
dataQuery: new Query().from('EventDatas'),
dataSource: new DataManager({
url: 'http://localhost:25255/api/Batch',
crossDomain: true,
adaptor: new UrlAdaptor(),
}),
}}
group={{
allowGroupEdit: false,
byGroupID: false,
resources: ['groupId', 'serviceId'],
}}
>
<ResourcesDirective>
<ResourceDirective
field='serviceId'
title='Services'
name='serviceId'
allowMultiple={true}
dataSource={services}
textField='serviceName'
idField='serviceId'
></ResourceDirective>
<ResourceDirective
field='groupId'
title='Group'
name='groupId'
allowMultiple={false}
dataSource={groups}
textField='name'
idField='groupId'
></ResourceDirective>
</ResourcesDirective>
<Inject
services={[
Day,
WorkWeek,
Month,
TimelineViews,
Resize,
DragAndDrop,
]}
/>
</ScheduleComponent>
</div>
</div>
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
You have missed to add CrudUrl in the dataManager settings. So that the CRUD actions are not working. So we would suggest you to refer and follow the below sample.
Service: https://www.syncfusion.com/downloads/support/directtrac/general/ze/ScheduleCRUD-1748824462-1972500097
Sample: https://stackblitz.com/edit/react-schedule-url-adaptor-two-level-resource?file=index.js
this.dataManger = new DataManager({
url: 'http://localhost:54738/Home/LoadData',
crudUrl: 'http://localhost:54738/Home/UpdateData',
crossDomain: true,
adaptor: new UrlAdaptor
});
UG: https://ej2.syncfusion.com/react/documentation/schedule/data-binding/#scheduler-crud-actions
We could reproduce the reported issue “issue in deleting the entire recurrence events” and confirm this as defect at our end. You can keep track of the bug through the following feedback. The fix for this issue is expected to be rolled out in in our JS2 weekly release scheduled on April 27, 2021. We would appreciate your patience until then.
Feedback: https://www.syncfusion.com/feedback/24505/issue-in-deleting-the-entire-recurrence-events-with-resources-only-when-it-is

how to pass dynamic value in the array using donutchart in reactjs

i am getting this response from back-end like this. how can i take this response in to state variable and how can i use the dynamic value to pass in this chart inside the data:[[ ]]array in reactjs. i am using in my code like this format. i need only dynamic value in this chart based on select the dropdown list select the one value(last day) and click on applying filter button. am sending the request and getting this (last day) response right. i need whatever value getting the response. i need to show dynamic value in this chats. based on applying the filter. how to do pass dynamic value in this data:[[]] array.
class Report extends React.Component {
constructor(props) {
super(props);
this.state = {
dashboardchart:{
series:[{
data:[]
}],
},
};
}
componentDidMount() {
UserAction._getdashboardchart();
}
_userStoreChange(type, value) {
if (type == 'DashboardChart') {
let dashboardchart = UserStore._getdashboardchart() || {};
this.setState({dashboardchart})
}
}
render() {
let chartdata = this.state.dashboardchart.series
const piechart = {
chart: {
type: 'pie',
options3d: {
enabled: true,
alpha: 45
}
},
title: {
text: 'Claim - Key Performance Indicators'
},
subtitle: {
text: ''
},
plotOptions: {
pie: {
innerSize: 100,
depth: 45
}
},
series: [{
name: 'Total consumption',
data: chartdata && chartdata.data && chartdata.data
}]
}
return (
<div className="panel-body">
<ReactHighcharts config={piechart}></ReactHighcharts>
</div>
);
}
}
export default Report;

How do we pass current object (this) with props and state to fullcalendar function?

I am using fullcalendar-scheduler plugin for following calendar. Currently
I have integrated it with react and rails.
I am trying to access this object from inside select function. For that I have added
const self = this;
But the self object is undefined inside select function. How can I get the self object
inside the select function?
import React from "react";
import PropTypes from "prop-types";
import axios from "axios";
class TestCalendar extends React.Component {
constructor(props) {
super(props);
this.state = {
cars: [],
events: [],
price: [],
selectDates: [],
startDate: moment(),
endDate: moment().add(3, 'years')
}
}
componentDidMount() {
const headers = {
'Content-Type': 'application/json'
}
axios.get('/api/v1/test_calendars?date_from=' + this.state.startDate.format(), { headers: headers })
.then(res => {
const cars = res.data;
this.setState({ cars });
});
axios.get('/api/v1/test_calendars/events?date_from=' + this.state.startDate.format(), { headers: headers })
.then(res => {
const events = res.data;
this.setState({ events });
});
axios.get('/api/v1/test_calendars/prices?date_from=' + this.state.startDate.format(), { headers: headers })
.then(res => {
const price = res.data;
this.setState({ price });
});
this.updateEvents(this.props.hidePrice);
}
componentDidUpdate() {
console.log('componentDidUpdate');
this.updateEvents(this.props.hidePrice);
console.log(this.state.cars);
}
componentWillUnmount() {
$('#test_calendar').fullCalendar('destroy');
};
handleChange(e) {
debugger;
}
updateEvents(hidePrice) {
function monthSelectList() {
let select = '<div class="Select select-me"><select id="months-tab" class="Select-input">' +
'</select></div>'
return select
}
function getDates(startDate, stopDate) {
var dateArray = [];
while(startDate.format('YYYY-MM-DD') <= stopDate.format('YYYY-MM-DD')) {
dateArray.push(startDate.format('YYYY-MM'));
startDate = startDate.add(1, 'days');
};
return dateArray;
}
const self = this; // Get this object in select function
$('#test_calendar').fullCalendar('destroy');
$('#test_calendar').fullCalendar({
selectable: false,
defaultView: 'timelineEightDays',
defaultDate: this.props.defaultDate,
views: {
timelineEightDays: {
type: 'timeline',
duration: { days: 8 },
slotDuration: '24:00'
}
},
header: {
left: 'prev',
right: 'next'
},
viewRender: function(view, element) {
let uniqueDates;
$("span:contains('Cars')").empty().append(
monthSelectList()
);
$("#months-tab").on("change", function() {
let index, optionElement, month, year, goToDate;
index = this.selectedIndex;
optionElement = this.childNodes[index];
month = optionElement.getAttribute("data-month");
year = optionElement.getAttribute("data-year");
goToDate = moment([year, (month - 1), 1]).format("YYYY-MM-DD");
$("#test_calendar").fullCalendar('gotoDate', moment(goToDate));
$("#months-tab").find("option[data-month=" + month + "][data-year=" + year + "]").prop("selected", true);
this.handleChange.bind(this)
});
let dates = getDates(moment(), moment().add(3, "years"));
uniqueDates = [...new Set(dates)];
$('#months-tab option').remove();
$.each(uniqueDates, function(i, date) {
$('#months-tab').append($('<option>', {
value: i,
text: moment(date).format('MMMM') + " " + moment(date).format('YYYY'),
'data-month': moment(date).format('MM'),
'data-year': moment(date).format('YYYY'),
}));
});
},
resources: this.state.cars,
resourceRender: function(resourceObj, labelTds, bodyTds) {
labelTds.css('background-image', "url(" + resourceObj.header_image + ")");
labelTds.css('background-size', "160px 88px");
labelTds.css('background-repeat', "no-repeat");
labelTds.css("border-bottom", "1px solid");
labelTds.addClass('resource-render');
labelTds.children().children().addClass("car-name");
},
resourceLabelText: 'Cars',
dayClick: function(date, jsEvent, view, resource) {
},
dayRender: function(date, cell){
cell.addClass('dayrender');
},
select: function(startDate, endDate, jsEvent, view, resource) {
// Get 'self' object here
},
events: this.state.events.concat(this.state.price),
eventRender: function(event, element, view){
},
schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives'
});
// Should stay after full component is initialized to avoid fc-unselectable class on select tag for months
$("#months-tab").on("mousedown click", function(event){event.stopPropagation()});
$(".prev-link").on("click", function(event){event.stopPropagation()});
$(".next-link").on("click", function(event){event.stopPropagation()});
}
render () {
return (
<div id='test_calendar'>
</div>
);
}
}
export default TestCalendar;

How to get Kendo UI grid React wrapper to refresh

I'm using the code below
Broke
const dataSourceSchema = {
model: {
fields: {
name: { type: 'string' },
description: { type: 'string' }
}
}
};
const gridOptions = {
...
};
class ItemsContainer extends React.Component {
componentDidMount() {
this.props.getItems();
}
render() {
const { items } = this.props;
const dataSource = {
schema: dataSourceSchema,
data: items
}
return (
<Grid {...gridOptions} dataSource={dataSource} />
);
}
}
And I get the following error
Error
But if I used this code that hard codes the dataSource.data then it works.
Works
const gridOptions = {
dataSource: {
data: [{name: 'foo', description: 'bar'}],
schema: {
model: {
fields: {
name: { type: "string" },
description: { type: "string" }
}
}
},
pageSize: 20
},
...
columns: [
"name",
"description"
]
};
class ItemsContainer extends React.Component {
componentDidMount() {
this.props.getItems();
}
render() {
const { items } = this.props;
return (
<Grid {...gridOptions}/>
);
}
}
What am I doing wrong. I was spreading out the dataSource property because it looks like the kendo wrapper is checking it's reference (as it should).

Resources