17

I have a react component, and I need debug the value of 'customer' element that 'map' produce "customers.map( customer =>".

I've tried before "" this

{ console.log (customer)}

but i get error, here the component:

const CustomersList = ({ data: {loading, error, customers }}) => {
    if (loading) {
        return <p style={{color:"red"}}>Loading ...</p>;
    }
    if (error) {
        return <p>{error.message}</p>;
    }

    return (
        <div>
            Customers List
            { customers.map( customer =>
                (<div  key={customer.id} >Hey {customer.firstname}</div>)
            )}
        </div>
    );
};
DDave
  • 1,400
  • 3
  • 16
  • 33
  • 2
    You are currently using a `map` with implicit return. Hence you are not able to `console.log()` within your map. Checkout @MayankShukla answer – Nocebo Sep 06 '17 at 08:31

3 Answers3

43

Use {} with arrow function for block body and put the console.log inside that, with block body you need to use return to return the ui elements.

Like this:

{ 
    customers.map( customer => {
        console.log(customer);
        return <div  key={customer.id} >Hey {customer.firstname}</div>
    })
}

As per MDN DOC:

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

Example:

var func = x => x * x;                  
// concise syntax, implied "return"

var func = (x, y) => { return x + y; }; 
// with block body, explicit "return" needed
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
0

A coworker showed me a trick to "log" out values not to the console, but rather to the browser, by adding another HTML element like this:

<pre>{JSON.stringify(customer.firstname)}</pre>
Z Kubota
  • 155
  • 1
  • 3
  • 11
0

Using a explicit return (as Mayank Shukla answer) is an option, but this is also possible with implicit returns (as the implementation in your question's example already have).

Hence console.log always returns undefined or "None" / void, we could use this to our advantage with optional chaining (||).

Example:

const CustomersList = ({ data: {loading, error, customers }}) => {
if (loading) {
    return <p style={{color:"red"}}>Loading ...</p>;
}
if (error) {
    return <p>{error.message}</p>;
}

    return (
    <div>
        Customers List
        {customers.map( customer =>
            console.log(customer) || (<div key={customer.id}>Hey 
{customer.firstname}</div>)
        )}
    </div>
    );
};
Foley
  • 58
  • 6