Home > Back-end >  Trying to run my application but suffering wth "Cannot read properties of undefined (reading &#
Trying to run my application but suffering wth "Cannot read properties of undefined (reading &#

Time:06-15

I'm trying to run a transactions application but Cannot read properties of undefined (reading 'reduce') error doesn't let me run the app. My screen turns into a full white btw. It was running just ok, and then suddenly boom, not working anymore: enter image description here

This is my Summary index.tsx:

import React, {useContext} from 'react'
import incomeImg from '../../assets/income.svg'
import outcomeImg from '../../assets/outcome.svg'
import totalImg from '../../assets/total.svg'
import { useTransactions } from '../../hooks/useTransactions'

import { Container } from './styles'

export function Summary() {

  const {transactions} = useTransactions()

  const summary = transactions.reduce((acc,transaction)=>{

    if (transaction.type === 'deposit'){
      acc.deposit  = transaction.amount
      acc.total  = transaction.amount
    } else {
        acc.withdraw = transaction.amount
        acc.total -= transaction.amount
      }

    return acc
    }, {
    deposit: 0,
    withdraw: 0,
    total: 0
  })

return (/*SOME HTML*/)

Also putting here my useTransaction hook: https://gist.github.com/gabrielforster/314e5a5f91d8f83c78a3cc8a56a55435

CodePudding user response:

Best to post the code for useTransactions(). Here I'm guessing that it is actually waiting for some data to complete. The best way to handle this is with a useEffect which fires when transactions is updated and put summary in a state. I added a optional chaining check .? to check for null or undefined before actually using reduce.

    const [summary, setSummary] = React.useState([])

    React.useEffect(() => {
        setSummary(transactions?.reduce(
            (acc, transaction) => {
                if (transaction.type === 'deposit') {
                    acc.deposit  = transaction.amount;
                    acc.total  = transaction.amount;
                } else {
                    acc.withdraw = transaction.amount;
                    acc.total -= transaction.amount;
                }

                return acc;
            },
            {
                deposit: 0,
                withdraw: 0,
                total: 0,
            },
        ));
    }, [transactions]);

CodePudding user response:

It was an error on my useTransaction hook guys! Thank you all floks

  • Related