Rafael Mora Rafael Mora - 1 year ago 127
React JSX Question

call function in a fetch promise without this

I would like to know, how do I do in order to call a function in a promise in a fetch?

Please note this line:

.then(json => this.processReq(json))

I have to use
because if don't it says that
. Shouldn't it be something like:
.then(json => processReq(json))
because of ES6 ??

this is my code (I'm using Babel ES6 and React):

import React, { Component, PropTypes } from 'react'
import fetch from 'isomorphic-fetch'

export default class Batchprodpry extends Component {
constructor(props) {
super(props) {
processReq(json) {
Object.keys(json).forEach(item => {
if (item === 'error') {
Object.keys(item).forEach(propry => {
alert('Conflicto! '+'\n'+
'Id: ' + JSON.stringify(propry.propryid)+'\n'+
'Id Operador: ' + JSON.stringify(propry.fkempid)+'\n'+
'Hora inicio: ' + JSON.stringify(propry.propryhoraini)+'\n'+
'Hora fin: ' + JSON.stringify(propry.propryhorafin))

postForm() {
let maq = this.state.obj['fkmaqid']
return fetch(`/scamp/index.php/batchprodpry/${maq}`, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
body: JSON.stringify(this.state.a)
.then(req => {
if (req.status >= 400) {
throw new Error("Bad response from server")
return req.json()
.then(json => this.processReq(json))
.catch(function(error) {
console.log('request failed', error)

Answer Source


Using a ES6 fat-arrow function means that this is bound to something else than the body of the function at hand.

If you used the ES5 syntax to express a similar function, this would be bound to the body of function and this.processReq would be undefined:

function (json) {
  return this.processReq(json);  // undefined

So an ES5 equivalent would have to be:

var self = this;
return fetch(...)
  .then(function (json) {
    return self.processReq(json);

As it happens in your particular example, this refers to the instance of Batchprodpry class. There is no local function with name processReq, only a method defined for the class instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download