React .trim() is not a function

13,593

Solution 1

You're setting what was a string to a number, and numbers don't have the trim() method on them. That's why it works the first time (when it's a string) and not the second time around:

array[key] = Number(array[key].trim());

So that code must be executing more than once.

Solution 2

linegraphdata[key].price is either null or not a string.

If there is a value, you can try using linegraphdata[key].price.toString().trim().slice(1)

You can check that price is a string with this ternary. If it's not a string it will set the value to -1

linegraphdata[key].price = Number(
    typeof linegraphdata[key].price == 'string' ? linegraphdata[key].price.trim().slice(1) : -1
 );
Share:
13,593

Related videos on Youtube

MrShedford
Author by

MrShedford

Updated on June 04, 2022

Comments

  • MrShedford
    MrShedford almost 2 years

    My application has a landing page with two components in two separate tabs.

    The code from the first component that is causing the crash looks like this:

    for (let key in linegraphdata) {
      linegraphdata[key].price = Number(
        linegraphdata[key].price.trim().slice(1)
      );
      linegraphdata[key].month = parseDate(linegraphdata[key].month);
    }
    

    When I load into my application initially it doesn't crash, loads the data from the first tab fine. I'll click into the second tab and when I eventually click back the whole application crashes and the log gives me this error:

    Uncaught TypeError: linegraphdata[key].price.trim is not a function
    

    It must have something to do with how React handles refreshing components once already rendered, could anyone help me figure it out please :)

  • Rayon
    Rayon over 5 years
    What if linegraphdata[key].price is null ? Cannot read property 'toString' of null
  • Andreas
    Andreas over 5 years
    If price was null the error would be a different one: "Uncaught TypeError: Cannot read property 'trim' of null"