0

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

2
  • 1
    It's saying products is not an array. Check your runtime environment. Are you sure you're passing in the data that you expect? console.log(products) and see what the value is right before you hit your error Commented May 16, 2021 at 23:18
  • products can't get any data of array, make sure you receive data with products, you can check with console.log(products), if everything is ok, then you need to check your internet connection or API logic with the postman or anything else. Commented May 16, 2021 at 23:38

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.