Harmeko Harmeko - 1 month ago 7
React JSX Question

Do i really need to use forceUpdate with fetch API and ReactJS

I'm using React and fetch() to develop an UI and I ended up doing this:

getOperatorsList: function ( obj ) {
fetch( 'http://x.x.x.x/operators.list',
{
method: 'GET',
credentials: 'include'
}
).then( function ( response ) {
return response.json()
} ).then( function ( json ) {
if ( json.statusCode === 3 ) {
cookieService.unsetCookie( 'sessId' );
}
obj.setState( { data: json }, () => obj.forceUpdate() );
} ).catch( function ( ex ) {
console.log( 'parsing failed', ex );
} )

}


This is called in my component Operators that looks like this

var Operators = React.createClass( {

getInitialState: function () {
return {
data: [{ "data": "Loading" }]
}
},

componentDidMount: function () {
operatorsService.getOperatorsList( this );
},

render: function () {
return (
<div>
<Row >
<Col>
<DataTablesCustom data={this.state.data} />
</Col>
</Row>
</div>
);
}
});


I already had a look at this question, and the code doesn't work for me.

This works fine but do I really need to use
forceUpdate()
or do I have a way to make the code "cleaner" ?

EDIT: there was a
setState
that looked like this
this.setState({stuff: stuff}, this.function()});
in a child component. I was able to remove
forceUpdate()
after changing the
setState
to
this.setState({stuff: stuff}, () => this.function()});
.

Answer

To get your code to work, you can try to do this in the service:

obj.setState.bind(obj)( { data: json });

However, there is no need to pass the component object to your service. Arguably, that's not such a good idea as you're just coupling things when it's not needed. Let the component call your service and then decide what to do with the data:

 getOperatorsList: function () {
    return fetch( 'http://x.x.x.x/operators.list', {
        method: 'GET',
        credentials: 'include'
    }).then( function ( response ) {
        return response.json()
    }).then( function ( json ) {
        if (json.statusCode === 3 ) {
            cookieService.unsetCookie( 'sessId' );
        }
        return json;
    }).catch( function ( ex ) {
      console.log( 'parsing failed', ex );
    })

}

Then in your component:

componentDidMount: function () {
    operatorsService.getOperatorsList()
    .then(function (json) {
       this.setState({ data: json });
    }.bind(this))
}
Comments