albert shmalbert
albert shmalbert

Reputation: 63

Why can't I return an object in React

Why does this always return an undefined in React with Redux?

searchCustomer = id =>{
customers = [...this.props.data];
customers.forEach(customer=>){if(customer.id === id){return customer}};
}

customerDetails = e =>{
const customer = this.searchCustomer(id);
console.log(customer);

}

The console log is always undefined. If you log the object before it's returned it shows the correct object, but you never get a return value in the customerDetail function.

Upvotes: 0

Views: 856

Answers (3)

Giang Le
Giang Le

Reputation: 7044

cause you can not return in forEach

change to

searchCustomer = id => this.props.data.find(customer => customer.id === id)

Upvotes: 2

Srdjan
Srdjan

Reputation: 582

You can't return the value from the forEach loop like that... Try using find function instead, it's muhc easier...

searchCustomer = id => {
    return this.props.data.find(customer => customer.id === id)
}

customerDetails = e => {
    const customer = this.searchCustomer(id);
    console.log(customer);
}

Upvotes: 1

Jayce444
Jayce444

Reputation: 9063

You aren't returning anything from searchCustomer. It should be

searchCustomer = id =>{
    customers = [...this.props.data];
    customers.forEach(customer=>){if(customer.id === id){return customer}};
    return customers;
}

Upvotes: -1

Related Questions