I am fetching data from an API using axios. On my invoice details page when I try to get data of only one invoice using this code
const id = props.match.params.id;
const invoice = useSelector((state) => state.invoices.find(invoice => invoice._id === id));
It returns an object or undefined but I only want an object inside an array or an empty array not undefined how should I do that? When I tried to use .filter method instead of .find, it logged the array into the console infinite time.
Complete code:
import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import backIcon from '../assets/images/icon-arrow-left.svg'
import InvoiceDetailsHeader from './InvoiceDetailsHeader';
import { useSelector } from 'react-redux';
// remove this after adding DB
import data from '../data.json'
import InvoiceCardDetails from './InvoiceCardDetails';
const InvoiceDetails = (props) => {
const [invoiceData, setInvoiceData] = useState([]);
const id = props.match.params.id;
const invoice = useSelector((state) => state.invoices.find(invoice => invoice._id === id));
useEffect(() => {
setInvoiceData(invoice);
// console.log(invoiceData)
}, [id, invoice]);
return (
<div className="mx-auto px-12 py-16 w-full max-w-3xl">
<Link to="/" className="text-neutral text-xs"><img className="inline -mt-1 mr-4" src={backIcon} alt="back" /> Go back</Link>
<InvoiceDetailsHeader data={invoiceData} />
<InvoiceCardDetails data={invoiceData} />
</div>
)
}
export default InvoiceDetails
Anyone please help me with this.
find()method returnsundefinedif element is not found. You can use an if condition to check ifinvoiceis undefined, and set it to an empty array if it is.