Nikolai Hegelstad Nikolai Hegelstad - 1 year ago 64
React JSX Question

How to set state in a function which is in a second JavaScript file?

I have a component in

which is calling a function in a second JavaScript file
, i wish to set the state of
to true when the createTimer function fails and
throws an error. This way I am able to show the
when the function has failed.

The error I'm getting is:
client.js:93 Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined

How can i show the error segment when the createTimer function fails?

Bonus question, how can I revert the state efficiently to false after let's say 5 seconds or whenever i perform another action.


const TimersDashboard = React.createClass({
getInitialState: function() {
return {
timers: [] ,
showError: false,
createTimer: function (timer) {
render: function () {
return (


window.client = (function () {
function createTimer(data) {
return fetch('/api/timers', {
method: 'post',
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',

function onError() {
this.setState({ showError: true; });

return {

Answer Source

Have onError as the part of TimersDashboard component and not client.js, and pass it into the createTimer function in addition to data:

    function createTimer(data, onError) { // onError is no longer a part of client.js 
                                          // it comes from TimersDashboard 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download