Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypedArray displays its values as NaN when rendering in ReactJS

I recently needed to use the Float32Array typed-array, which will be used to render a list of elements (regardless in what type of format - e.g. an <ul> with <li> as each element of my array). For some reason, when I try to render the values, I get NaN even though the isNaN() call returns false moreover the typeof of each element is number and the console prints just fine the values. For example:

class App extends Component {
  constructor(props) {
    super(props);

    this.state = { channels: new Float32Array([1, 2, 3, 4]) };
  }

  render() {
    return (
      <ul>
        {this.state.channels.map((val, index) => (
          <li key={index}>{val}</li>
        ))}
      </ul>
    );
  }
}

export default App;

This one prints a series of NaNNaNNaNNaN (not even distributing them in proper <li> elements. I expect to have the values printed as they are already stored in the array.

Is there any reason for which the rendering doesn't work for types arrays (as expected) but works just fine in console logging? (or am I doing actually something wrong?)

Thanks!

like image 381
Shmwel Avatar asked Feb 11 '19 22:02

Shmwel


1 Answers

The reason it's doing that is because Float32Array#map() expects the callback to return a number, and the method itself returns a Float32Array. What you'd want to do is convert it to an Array first and then map it:

Array.from(this.state.channels).map((val, i) => ...)
like image 198
coolreader18 Avatar answered Oct 10 '22 12:10

coolreader18