I can see array with objects of data "fees" perfectly but if i wanna see a single value like fees[0]?.firstFee i get this error:
Uncaught TypeError: Cannot read properties of undefined (reading '0')
i thought ? operator would avoid this but seems like not...
const [fees, setFees] = useState();
useEffect(() => {
const getFees = async () => {
const res = await axios.get('/api/feesettings', {
headers: { Authorization: token },
});
setFees(res.data);
};
getFees();
}, []);
console.log(fees);
console.log(fees[0]?.firstFee );
CodePudding user response:
The reason why you are getting an error on every render is because, you are passing no value to the state, so by default fees is undefined
const [fees, setFees] = useState();
and when you reach this line of code, you are trying to access fees[0] as if fees is an array, it is not that's why it's giving you an error Cannot read properties of undefined (reading '0')
console.log(fees[0]?.firstFee);
So change to this line of code,
const [fees, setFees] = useState([]);
if (fees.length > 1) {
console.log(fees[0]?.firstFee);
}