skip to Main Content

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


  1. Have you tried this?

    setDataCards(dataCards => [...dataCards, ...dataArray])
    

    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

    Login or Signup to reply.
  2. You are concatenating the current dataCards state array with the new dataArray each time the useEffect hook runs. This causes duplicates to be added to the dataCards state on each render.

    To fix this, you can simply set the dataCards state to dataArray without concatenating the two arrays.

    const [dataCards, setDataCards] = useState([]);
    
    useEffect(() => {
      if (Object.keys(userWidgetDetails).length > 0) {
        const { widgets } = userWidgetDetails;
        const dataArray = widgets.filter((s) => s.type === "card");
        setDataCards(dataArray);
      }
    }, [userWidgetDetails, customizeWidget]);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search