Emmanuel Oga
Emmanuel Oga

Reputation: 99

React js reduce error : Type error: produts.reduce is not a function

I do not what is causing the error TypeError: products.reduce is not a function

enter image description here

Code

import React, {useState, useEffect} from 'react';


const Checkout = ({ products }) => {
    const getTotal = () => {
        return products.reduce((currentValue, nextValue) => {
            return currentValue + nextValue.quantity * nextValue.price;
        }, 0)
    };

    return<div>
        <div>Total: ${getTotal()}</div>
    </div>
}

export default Checkout;

Thank you for your help

Upvotes: 0

Views: 4937

Answers (1)

Heri Hehe Setiawan
Heri Hehe Setiawan

Reputation: 1633

As pointed out in the comments, this might be caused by products property not having a value.

This can simply be fixed by adding a default value of the property:

import React, {useState, useEffect} from 'react';


const Checkout = ({ products = [] }) => {
    const getTotal = () => {
        return products.reduce((currentValue, nextValue) => {
            return currentValue + nextValue.quantity * nextValue.price;
        }, 0)
    };

    return<div>
        <div>Total: ${getTotal()}</div>
    </div>
}

export default Checkout;

or:

import React, {useState, useEffect} from 'react';


const Checkout = ({ products }) => {
    const getTotal = () => {
        return (products || []).reduce((currentValue, nextValue) => {
            return currentValue + nextValue.quantity * nextValue.price;
        }, 0)
    };

    return<div>
        <div>Total: ${getTotal()}</div>
    </div>
}

export default Checkout;

Or return default value earlier:

import React, {useState, useEffect} from 'react';


const Checkout = ({ products }) => {
    const getTotal = () => {
        if (!Array.isArray(products)) {
            return 0;
        }
        return products.reduce((currentValue, nextValue) => {
            return currentValue + nextValue.quantity * nextValue.price;
        }, 0)
    };

    return<div>
        <div>Total: ${getTotal()}</div>
    </div>
}

export default Checkout;

Upvotes: 1

Related Questions