Lodash 'get' not working when use in a Arrow Function (React)

Viewed 630

I'm using Lodash in a project and I'm trying to use the get function in order to filter some data to activate a button to save some data to an endpoint, but when I use the get inside of an Arroe Function it returns undefined, then I use the same code in a variable assignation works properly, you can check the error in this StackBlitz. Someone else getting this kind of error? Thanks in advance.

componentDidMount() {
  const checkMandatory = tab => {
    get(this.state.data, [tab, 'data', 'datosCalculados'], []);
  };
  const obligatorios = checkMandatory('ingresos');
  const obligatorios2 = get(this.state.data, ['ingresos', 'data', 'datosCalculados'], []);
  console.log('Obligatorios: ', obligatorios);
  console.log('Obligatorios2: ', obligatorios2);
}
2 Answers

return was missing

Instead of

const checkMandatory = tab => {
  get(this.state.data, [tab, 'data', 'datosCalculados'], []);
};

do

const checkMandatory = tab => { 
  return get(this.state.data, [tab, 'data', 'datosCalculados'], []); 
};

or better yet:

const checkMandatory = tab => get(this.state.data, [tab, 'data', 'datosCalculados'], []);

resulting in:

enter image description here

My error was not returning the value on the checkMandatory validator function, to solve it:

const checkMandatory = tab => get(this.state.data, [tab, 'data', 'datosCalculados'], []);
Related