새소식

🍪 Study/웹

[React] map() vs forEach(): Array.prototype.map() expects a return value from arrow function.

  • -
728x90

WARNING in [eslint]
src/components/views/MainPage/index.js
    Line 241:24: Array.prototype.map() expects a return value from arrow function.


The error you're seeing, Array.prototype.map() expects a return value from arrow function, occurs because the map function is used incorrectly. The map function expects a return value from the arrow function used within it. If you don't need to transform the array but just want to iterate over it, you should use forEach instead of map.

Here's how you can correct the code:

  1. Replace map with forEach to avoid the error.
  2. Ensure that you are returning a value if you decide to use map.

Here's the corrected version of your onClickTR function:

const onClickTR = (data) => {
  Axios.post(`${ADMIN_SERVER}/labelbyuserdate`, {
    user_id: data.user_id,
    date: data.date.replaceAll("-", "/"),
  }).then((res) => {
    if (res.status === 200) {
      // console.log(res.data.data);
      setSeries3([{ data: res.data.data }]);
    }
  });

  var newSeriesData = [];
  dataset.forEach((d) => {
    if (d.user_id === data.user_id && d.date === data.date) {
      newSeriesData.push({
        x: d.x.toString(),
        y: [
          new Date(`${d.date} ${d.start}`).getTime(),
          new Date(`${d.date} ${d.end}`).getTime(),
        ],
        label: d.label,
      });
    }
  });

  setSeries4([{ data: newSeriesData }]);
};

Explanation:

  1. Replaced map with forEach:
    • map is used for transforming each element of an array and returning a new array with the transformed elements.
    • forEach is used for iterating over each element of an array without returning a new array. Since you're not transforming the array but rather pushing elements into newSeriesData, forEach is appropriate here.
  2. Corrected the iteration:
    • The function now iterates over dataset with forEach, pushing the filtered and formatted data into newSeriesData.

This should resolve the error and ensure that the function behaves as expected.

728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.