Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - sorting - TypeError: 0 is read only

I'm trying to sort an object before mapping it in reactjs, but every single time I do, I keep getting the TypeError: 0 is read only. I noticed that on load the props are empty, but even when I was trying to check the length of the array and only apply sort when it's higher than 0, or when the array exists to be precised, it would still happen. The moment I try to sort anything, it just stops working.

I would like to be able to sort these via different criteria in the future, but so far I can't even go through regular sorting on render...

I have the below:

ToysList.jsx

import React, { Component } from 'react';
import PropTypes from 'prop-types';


class ToysList extends Component {
  constructor (props) {
    super(props);
    this.state = {};
}


render () {
    var toys = this.props.toys;
    var arr = toys.sort((a,b) => parseFloat(a.price) - parseFloat(b.price));

    return (
        <div>
            <div key="list">
               { arr.map((toy, index) => (
                    <div key={toy.id}>
                        {toy.name}:<br/>
                        Quantity: {toy.quantity}<br/>
                        Price: {toy.price}<br/>
                        Rating: {toy.rating}
                    </div>
                )) }
            </div>
        </div>
    );
}
}

ToysList.propTypes = {
toys: PropTypes.arrayOf(
    PropTypes.shape({
        id: PropTypes.string,
        name: PropTypes.string,
        quantity:PropTypes.number,
        price:PropTypes.number,
        rating:PropTypes.number,
    }),
).isRequired,
};


export default ToysList;

I'd be grateful for any hint with these. Thanks

like image 371
Entalpia Avatar asked Mar 14 '18 13:03

Entalpia


1 Answers

That could be because sort mutates the array it works on (it sorts in-place).

If this.props.toys is immutable then it would throw that error.

Create a copy of the array and sort that.

var toys = this.props.toys.slice();
// var toys = Array.from(this.props.toys);
// var toys = [...this.props.toys];
var arr = toys.sort((a,b) => parseFloat(a.price) - parseFloat(b.price));
like image 125
Gabriele Petrioli Avatar answered Oct 05 '22 23:10

Gabriele Petrioli