Home > Enterprise >  Function throws error when trying to run a second time
Function throws error when trying to run a second time

Time:09-26

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: screenshot of the 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!

CodePudding user response:

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.

CodePudding user response:

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

Double check if it's not an object.

  • Related