0

I gave conditions to if in useEffect() to wait data for fetched..
invoice && invoice['data'] like this.
My expectation was setMoney() would work. but It just passes this function.
invoice is fetched data from store.

This is view compoenet.

import React, {useContext, useEffect, useState} from 'react';
import './invoice.scss';
import InvoiceFilter from './invoice_filter';
import InvoiceTable from './invoice_table';
import {invoiceContext} from '@/context/invoice_dataStore';

function Invoice(props) {
  const {invoice, getInvoiceInitialData} = useContext(invoiceContext);
  const [receivable, setReceivable] = useState(0);
  const [pending, setPending] = useState(0);

  useEffect(() => {
    if (invoice && invoice['data']) {
      setMoney();
    }
  }, []);

  function setMoney() {
    if (invoice && invoice['data']) {
      const infoSt = invoice['data'].map((info) => info);
      infoSt.forEach((info) => {
        switch (info.status) {
          case 100: //receivable
            setReceivable((prev) => prev + info.amount);
            break;
          case 200: // Pending
            setPending((prev) => prev + info.amount);
            break;
          default:
            throw new Error('unknown command');
        }
      });
    }
  }


  return (
    <React.Fragment>
      <div className="invoice">
          <strong>${receivable}</strong>
          <strong>$ {pending}</strong>
       </div>
    </React.Fragment>
  );
}

export default Invoice;

  • Edited
    before using useEffect(), I approached this using only if.
    and I don't still get why this didn't work.!
if(invoice && invoice['data']){
    setMoney();
  }

because this worked.

let showTable;
if(invoice && invoice['data']){
    showTable = invoice['data'].map((info) => 
      <div>{info.title}</div>)
    }
  }


return (
    <>
     {showTable}
    </>
)
bonlim
  • 163
  • 9

1 Answers1

1

useEffect with empty dependency array is only called after the initial component mount. It's highly possible that the invoice data in your context wasn't populated at the time of the useEffect execution.

To fix this, you have to pass invoice as a dependency to the useEffect hook so that your function can execute when its value changes.

useEffect(() => {
    if (invoice && invoice['data']) {
      setMoney();
    }
  }, [invoice]);
slumbergeist
  • 1,438
  • 12
  • 18