Nikolai Hegelstad Nikolai Hegelstad - 3 months ago 11
React JSX Question

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

I have a component in

app.js
which is calling a function in a second JavaScript file
client.js
, i wish to set the state of
showError
to true when the createTimer function fails and
checkStatus
throws an error. This way I am able to show the
ErrorSegment
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.

app.js:

const TimersDashboard = React.createClass({
getInitialState: function() {
return {
timers: [] ,
showError: false,
};
},
createTimer: function (timer) {
client.createTimer(t);
},
render: function () {
return (
<ErrorSegment
showError={this.state.showError}
/>
);
},
});


client.js:

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

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

return {
createTimer,
};
}());

Answer

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 
Comments