I have an array of objects
const w=[ {widgetId: 13, widgetKey: "currentMonthAvgSalesOrders", widgetName: "Current month average sales and orders", title: "Current month average sales and orders", type: "card", …},
{widgetId: 12, widgetKey: "orderSalesCurrentFinancialYear", widgetName: "Sales and orders of the current financial year", title: "Sales and orders of current financial year", type: "card", …},
{widgetId: 28, widgetKey: "currentMonthAvgSalesPerSectorPerDay", widgetName: "Current Month Average Sales per sector per day", title: "Current Month Average Sales per sector per day", type: "card", …},
{widgetId: 28, widgetKey: "currentMonthAvgSalesPerSectorPerDay", widgetName: "Current Month Average Sales per sector per day", title: "Current Month Average Sales per sector per day", type: "card", …}]
I am storing it in a setState function which is initially an empty array by filtering based on criteria. I am using the rest operator to store the data in the setState but it gives me duplicate data which keeps adding up each time I call the useEffect
hook.
My useState
hook:
const [dataCards,setDataCards]=useState([]);
useEffect(() => {
if(Object.keys(userWidgetDetails).length>0){
const {widgets}=userWidgetDetails;
let dataArray=widgets.filter(s=>s.type==='card')
setDataCards([...dataCards,...dataArray])
}
}, [userWidgetDetails,customizeWidget])
what is wrong with this implementation?
2
Answers
Have you tried this?
This will allow you to make use of the current values of the state variable, which is the argument passed in to the
setDataCards
function.More info: https://react.dev/reference/react/useState#setstate
You are concatenating the current
dataCards
state array with the newdataArray
each time theuseEffect
hook runs. This causes duplicates to be added to thedataCards
state on each render.To fix this, you can simply set the
dataCards
state todataArray
without concatenating the two arrays.