Home > database >  ReactHook adding array of an array state without duplicating the key
ReactHook adding array of an array state without duplicating the key

Time:10-01

I am trying to add data grouping by the unit name for showing functionality

const [allData , setAllData]= useState([{'unit':'' , data:[]}])   

 useEffect(async () => {
        await axios.get(`${BACKEND_URL}/data`).then(res => {
            res.data.map(elem => {
                setAllData(prev =>[...prev , { 'unit': elem.unitName, 'data': [elem.lessonName] }]);
            });
        });
    }, []);

the result is duplicating the key for the subarray which is "unit" for my exampl:

[
    {
        "unit": "unit 1",
        "data": [
            "LO1"
        ]
    },
    {
        "unit": "unit 2",
        "data": [
            "LO2"
        ]
    },
    {
        "unit": "unit 3",
        "data": [
            "LO3"
        ]
    },
    {
        "unit": "unit 1",
        "data": [
            "LO15"
        ]
    }
]

CodePudding user response:

Try like that, if find unique property unit rewrite data or push new element to array

  useEffect(async () => {
    await axios.get(`${BACKEND_URL}/data`).then(res => {
        setAllData((prev) => {
          let result = [...prev];
          res.data.forEach(({ unitName: unit, lessonName }) => {
            const index = result.findIndex((elem) => elem.unit === unit);
            if (index >= 0) {
              result[index].data = [...result[index].data, lessonName]
            } else {
              result.push({unit, data: [lessonName]});
            }
          });
          return result;
        });
    });
  }, []);
  • Related