I am using react useState to make a demo. I am facing below error while I am trying to print my expenses data inside Expenses component. if I am passing data without useState it is working but if I am using useState it is not working.
Error
Uncaught TypeError: props.expenses.map is not a function
at Expenses (Expenses.js:18:1)
at renderWithHooks (react-dom.development.js:14985:1)
at updateFunctionComponent (react-dom.development.js:17356:1)
at beginWork (react-dom.development.js:19063:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork$1 (react-dom.development.js:23964:1)
at performUnitOfWork (react-dom.development.js:22776:1)
at workLoopSync (react-dom.development.js:22707:1)
My code
import { useState } from "react";
import "./App.css";
import Expenses from "./components/Expenses/Expenses";
import NewExpense from "./components/NewExpense/NewExpense";
const DUMMY_DATA = [
{
id: "ex1",
title: "expense item 1",
amount: 120,
date: new Date(2022, 2, 22),
},
{
id: "ex2",
title: "expense item 2",
amount: 100,
date: new Date(2022, 2, 23),
},
{
id: "ex3",
title: "expense item 3",
amount: 90,
date: new Date(2022, 2, 20),
}
];
function App() {
const [expenses, setExpenses] = useState(DUMMY_DATA);
const onAddExpenseHandler = (expense) => {
setExpenses((prevExpenses) => {
return { expense, ...prevExpenses };
});
};
return (
<div className="App">
<NewExpense onAddExpense={onAddExpenseHandler} />
<Expenses expenses={expenses} />
</div>
);
}
export default App;
Problem was return type of state. I was returning object instead of array. I have set some dummy expenses data which is type of array. so returning array instead of object fixed my issue. As I was passing object it was not able to loop through array and was giving error.
setExpenses((prevExpenses) => {
return { expense, ...prevExpenses }; //Problem here
});
Solution:
setExpenses((prevExpenses) => {
return [expense, ...prevExpenses]; //use array over here
});