Link to home
Start Free TrialLog in
Avatar of ocean O
ocean OFlag for United States of America

asked on

How to sort the React immutable data structure?

I am new to react js. I am working on a sorting function. Below is my code. When it run the line of :   manList:  newManList.sort( (a, b) => (, I got an error that : The sort method cannot be invoked on an Immutable data structure.  How can I make the newManList variable as a mutable data structure?

Thanks


isHeaderClickable(key){
    let newManList = this.props.mans;
    this.setState({
        manList:  newManList.sort( (a, b) => (
            this.state.direction[key] === 'asc'
                //? parseFloat(a[key]) - parseFloat(b[key])
               // : parseFloat(b[key]) - parseFloat(a[key])
                ? (a[key]) - (b[key])
                : (b[key]) - (a[key])
               )),
        direction: {
            [key]: this.state.direction[key] === 'asc' ? 'desc' : 'asc'
        }

    })

    },
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Try to use toJS() method as the following example..
 isHeaderClickable(key){
    let newManList = this.props.mans;
    this.setState({
        manList:  newManList.sort( (a, b).toJS() => (
            this.state.direction[key] === 'asc'
                //? parseFloat(a[key]) - parseFloat(b[key])
               // : parseFloat(b[key]) - parseFloat(a[key])
                ? (a[key]) - (b[key])
                : (b[key]) - (a[key])
               )),
        direction: {
            [key]: this.state.direction[key] === 'asc' ? 'desc' : 'asc'
        }

    })

    }

Open in new window

Avatar of ocean O

ASKER

No, it is not working. I had figured out w way to do it. I have another question, How can I pass the new state back to the page. like:
  [actionTypes.LIST_SORT]: (state, action) => {
      let newState = {...state,[action.uniqueKey]: action.payload};
        return state.merge({newState})
    },

I defined an action: list_Sort, and I want to return the newstate back to page. How can I do it?

Thanks
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.