Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to console.log() this function?

I'd like to generate JSX for React-Native, yet I do want to examine each key/value using console.log().

what I am after:

{Object.keys(this.state.types).map((obj) => (
          console.log(obj); <-- This guy
          <Item label={obj[TYPE]} value={obj[ID]} />
          ))}

But an Error is thrown "Unexpected token"

How can I still debug my values inside map?

like image 688
Ted Avatar asked Jan 08 '17 14:01

Ted


2 Answers

You can use the comma operator:

 {Object.keys(this.state.types).map((obj) => (
      console.log(obj), <-- This guy
      <Item label={obj[TYPE]} value={obj[ID]} />
      ))}

Which evaluates the statement and then discards it, or you can use the || operator which will evaluate console.log which returns false and then will return the React element:

 {Object.keys(this.state.types).map((obj) => console.log(obj) || (

      <Item label={obj[TYPE]} value={obj[ID]} />
      ))}

However, both are fairly hacky, I recommend you turn your arrow function into a multi-line arrow and just use return:

 {Object.keys(this.state.types).map((obj) => { 
      console.log(obj);
      return <Item label={obj[TYPE]} value={obj[ID]} />
  })}

On a side note - don't forget to set the key property on your objects returned from an array or you'll get a performance slowdown and a warning (you're currently not doing this).

like image 171
Gal Zohar Avatar answered Sep 23 '22 18:09

Gal Zohar


The round brackets in => ( tell the function that it's returning an object (JSX is transpiled into a JS object). You want a function body to run console.log(), and then return the <Item> element.

Convert the round brackets to curly ones, and add a return statement:

{Object.keys(this.state.types).map((obj) => {
  console.log(obj); <-- This guy
  return (
    <Item label={obj[TYPE]} value={obj[ID]} />
  );
})}
like image 45
Ori Drori Avatar answered Sep 25 '22 18:09

Ori Drori