react developer tool incorrect state - reactjs

I am using react developer tool in my browser and I dont know why its not showing the correct values. I tried console.log and in my console it shows the correct value.
I got this code
axios.all(promisesChoices).then(() => {
console.log(Choices);
self.setState({ Choices });
console.log(self.state.Choices);
});
and it shows
but on my react dev tool
Anyone encountered this?

setState is async, so if you want to verify that it worked correctly, you can do so in its calllback function:
axios.all(promisesChoices).then(() => {
console.log(Choices);
self.setState({
Choices
}, () => {
console.log(self.state.Choices);
});
});

Related

close the tab by asking a confirmation box in react js

I'm trying to add this custom message using the below code but it's showing the default message. please help me where I'm doing wrong thanks in advance
window.addEventListener("beforeunload", (ev) => {
ev.preventDefault();
return ev.returnValue = 'Are you sure you want to close?';
});
This dialog looks like chrome, and chrome removed the option to customize this message, see here: https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en#remove_custom_messages_in_onbeforeunload_dialogs
Also this answer claims it's not only chrome, but most browsers https://stackoverflow.com/a/38880926/299774

'Dashboard not a constructor' error with Google Charts

I am a naive React Developer and facing some difficulty with getting gooogle chart work with react. I am using Google Charts in a ReactJs component with ControlWrapper as shown below.
componentDidMount: function(){
google.charts.load('current', {'packages':['corechart', 'controls']});
this.drawCharts();
},
componentDidUpdate: function(){
google.charts.load('current', {'packages':['corechart', 'controls']});
this.drawCharts();
},
drawCharts: function(){
var cmpt = this;
//Removed detailed code from here due to copyright issues
//adding controls----------------
let dashboard = new google.visualization.Dashboard( document.getElementById(cmpt.props.widgetId) );
let controlId = '${this.props.widgetId}_control';
var controlWrapper = new google.visualization.ControlWrapper({
'controlType' : 'NumberRangeFilter',
'containerId' : controlId,
'options' : {
'filterColumnLabel' : xDataSysName
}
});
var barChart = new google.visualization.ChartWrapper({
'chartType': 'BarChart',
'containerId': this.props.widgetId,
'options': options
});
dashboard.bind(controlWrapper, barChart);
dashboard.draw(data);
if(linkColumn){
let selectionEventHandler = function() {
window.location = data.getValue(barChart.getSelection()[0]['row'], 1 );
};
google.visualization.events.addListener(barChart, 'select', selectionEventHandler);
}
}
},
This is not the whole piece of code but should be enough for the issue I'm facing.
First time I load the page, I get the error in the console saying
google.visualization.Dashboard is not a constructor
I reload the page hitting SHIFT+F5, the error goes away and components load just fine except ones that are dependent on controlWrapper throwing the error as follows
google.visualization.controlWrapper is not a constructor
which never goes away even after reloading the page. I referred to this discussion and tried their solution but I am still getting these error in the manner mentioned above. Please help me figure out how to fix it. Also, I am not able to comprehend why dashboard error goes away on a reload.
need to wait until google charts has fully loaded before trying to use any constructors,
this is done by providing a callback function.
try changing the load statement as follows...
componentDidMount: function(){
google.charts.load('current', {packages:['corechart', 'controls'], callback: this.drawCharts});
},
componentDidUpdate: function(){
google.charts.load('current', {packages:['corechart', 'controls'], callback: this.drawCharts});
},

React keep data attribute

I have to do a 'simple' task. It is actually simple if you know the react framework or have any Javascripts knowledge in particular but my Javascript knowledge is pretty terible so I am really stuck now.
What I am trying to achieve is, I have a button 'terminate' in a table (so several rows). When I click the button, I want the console log to throw me the transactionID of that row. But I really cannot get it to work. This is what I have currently:
I have a class with in it several methods, of one is a 5 sec auto refresh function:
var ExceptionalCases = React.createClass({
I created this method:
TerminateCase: function(e) {
e.preventDefault();
this.setState({
}, function() {
var transactionID = this.refs.transid.target.getAttribute("data-transid");
console.log('button clicked' + transactionID);
}.bind(this));
},
And this is the button (located in the render):
<input type="button" name="TerminateCase" value={_('Terminate')} style={{width: '110px'}}
onClick={this.TerminateCase} ref="transid" data-transid={entry.transactionId}/>
This is the error I get:
TypeError: this.refs.transid.target is undefined
I am clueless, I searched alot and tried many different approaches but I am really stuck now. I hope that someone can help me ;-(
Try this:
TerminateCase: function(e) {
e.preventDefault();
var transactionID = e.currentTarget.getAttribute("data-transid");
console.log('button clicked' + transactionID);
}

Angular 1.x/2 Hybrid, karma tests not bootstrapping ng1 app

I currently have a Hybrid Angular app (2.4.9 and 1.5.0) using angular-cli. Currently, when running our application, we are able to bootstrap the 1.5 app correctly:
// main.ts
import ...
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
angular.element(document).ready(() => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.body, ['myApp'], {strictDi: true});
});
});
However, in our test.ts file:
// test.ts
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import ...;
declare var __karma__: any;
declare var require: any;
__karma__.loaded = function () {};
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
// I'm assuming that I need to call 'boostrapModule()' somehow here...
platformBrowserDynamicTesting()
);
const context = require.context('./', true, /\.spec\.ts$/);
context.keys().map(context);
__karma__.start();
I'm not exactly sure how to bootstrap our 1.5 application into the test environment, all I've gotten is Module 'myApp' is not available!, and my Google skills have failed trying to find an example.
I was hoping the bounty I added last night would mean I could log on this morning to a nice solution laid out for me. Alas, it did not. So instead I spent the day cruising around many SO answers and github issues getting it to work. I'm sorry I did not keep track of everything that helped me to credit them, but here is my solution. It is probably not ideal, but it is working so far so I hope it is a good start.
This github issue indicates that downgradeComponent isn't going to work for now, so I went with what I assume is an older technique using UpgradeAdapter. Note that this technique does not use initTestEnvironment. Here are the relevant snippets, with some explanations below:
// downgrade.ts:
export const componentsToDowngrade = {
heroDetail: HeroDetailComponent,
...
};
export function downgradeForApp() {
forOwn(componentsToDowngrade, (component, name) => {
app.directive(name!, downgradeComponent({ component }));
});
}
// main.ts:
downgradeForApp();
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory).then((platformRef) => {
...
});
// test.ts:
require("../src/polyfills.ts");
require("zone.js/dist/proxy");
require('zone.js/dist/sync-test');
require("zone.js/dist/mocha-patch");
// test-helper.ts
let upgradeAdapterRef: UpgradeAdapterRef;
const upgradeAdapter = new UpgradeAdapter(AppModule);
forEach(componentsToDowngrade, (component, selectorName) => {
angular.module("app").directive(
selectorName!,
upgradeAdapter.downgradeNg2Component(component) as any,
);
});
export function useAdaptedModule() {
beforeEach(() => {
upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(["app"]);
});
}
export function it(expectation: string, callback: () => void) {
test(expectation, (done) => {
inject(() => { }); // triggers some kind of needed initialization
upgradeAdapterRef.ready(() => {
try {
callback();
done();
} catch (ex) { done(ex); }
});
});
}
// hero-detail.component.spec.ts
import { it, useAdaptedModule } from "test-helpers/sd-app-helpers";
describe("", () => {
useAdaptedModule();
it("behaves as expected", () => { ... });
});
A few of the highlights from that code:
I downgrade components differently for tests than for the app, so I made a DRY list of them in downgrade.ts
I downgrade components for the main app from main.ts by calling downgradeForApp() as shown above (used with AOT for a production bundle), and also main-jit.ts, not shown above (used for development)
I showed the imports I needed to add to start integrating Angular components into my AngularJS tests. You may need more/different ones depending e.g. on whether your tests are asynchronous, or you use Jasmine instead of Mocha.
At the beginning of each test that needs to use downgraded components, I "bootstrap" things with useAdaptedModule() instead of beforeEach(angular.mock.module("app"));
I import an alternative it from my helpers, which wraps the it provided by Mocha. None of my tests are asynchronous; if you have some that are it may require tweaking. I do not know how it may need to be adapted for Jasmine.
A caveat: Instantiating the component must happen within an it callback so that it happens within upgradeAdapterRef.ready(...). Trying to do it within a beforeEach is too soon.

ExtJS 4.1: unload event

I am working with ext js 4.1. I am developing an application that have to support IE9, the latest Firefox, the latest Chrome and Safari.
I need to show an alert message when the user wants to leave the if there are some data that is pending to submit.
I did the following using raw Javascript:
window.onbeforeunload=function(){
if (Ext.getStore('LocalChangesStore')){
if (Ext.getStore('LocalChangesStore').getCount() > 0) {
return 'Your changes are be lost.';
}
}
};
I am wondering if that would be possible with ext js. I saw the following function:
app.js:
EventManager.onWindowUnload( function(){
if (Ext.getStore('LocalChangesStore')){
if (Ext.getStore('LocalChangesStore').getCount() > 0) {
return 'Your changes are be lost.';
}
}
}, this
);
but it did not work.
Can somebody let me know which would be the best approach to solve this issue?
The onWindowUnload method attachs a function to the unload event but what you need is attach a function to the beforeunload event. Try this please
Ext.EventManager.on(window, 'beforeunload', function() {
return 'Your changes are be lost.';
});
Good luck.

Resources