Rafael Mora Rafael Mora - 3 months ago 10
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
this.
because if don't it says that
processReq
is
undefined
. 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') {
console.log('item',JSON.stringify(item))
Object.keys(item).forEach(propry => {
console.log('propry',JSON.stringify(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

No.

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.

Comments