简体   繁体   中英

Function throws error when trying to run a second time

I have a problem with a download button. If I reload the page, the onClick={() => ExportAll(data)} works fine the first time when pressing the download button, however when I try it after that the console throws this error: 错误截图

The function itself looks like this:

const exportAll = (data) => {
    const arr = []
      data.map((element) => {
            element.orderlines = element?.orderlines?.join(' , ')
            arr.push(element)
          }
      );
      exportFileAsXLSX(arr, `Meest recente orders-${props.timespan}`);
  };

The data object is set using the useState hook

If anyone has any idea why this doesn't work, please let me know!

const exportAll = (data) => {
    const arr = []
      data.map((element) => {
            let newElement = { ...element}
            newElement.orderlines = element?.orderlines?.join(' , ')
            arr.push(newElement)
          }
      );
      exportFileAsXLSX(arr, `Meest recente orders-${props.timespan}`);
  };

At first execution you overwrite original objects orderlines field value. Then at the next time you try to apply join operation to that field value again. Now it is a string not an array. That is the reason for the error.Change the code as above it will work.Above code I create a new obj rather than overwriting it.

Is orderlines an array? Cause you can only use join() if it is indeed an array!

Double check if it's not an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM