your uncle
your uncle

Reputation: 53

TypeError: Cannot read properties of undefined (reading 'reduce')

If the function is in a component, then everything works fine. if I take it out separately and export it to a component, then I get an error TypeError: Cannot read properties of undefined (reading 'reduce')

const getAverageScores = (data) => {
    return data.reduce((acc, {value}) => acc + value, 0) / data.length;

}

Help me please

useEffect(() => {
    if (data.length) {
         setAverage(getAverageScores(data))
    }
}, [data])

and I use getAverageScores there

export  const getStandardDeviation = (data) => {
const total = 0;
const averageScore = getAverageScores()
const squaredDeviations = data.reduce((total, data) => {
    const deviation = data && data.value - averageScore;
    const deviationSquared = deviation * deviation;

    return total + deviationSquared;
}, total);

return Math.sqrt(squaredDeviations / data.length);

}

Upvotes: 3

Views: 36158

Answers (1)

Federkun
Federkun

Reputation: 36924

You are calling getAverageScores with undefined.

const averageScore = getAverageScores()

should be

const averageScore = getAverageScores(data)

Upvotes: 2

Related Questions