2

I am building an internal messaging app with React-Redux using GiftedChat to display my messages. However they are always in the wrong chronological order. So I figure I'll sort the array in my view. However, it doesn't seem to be working and I can't figure out why. This is what it looks like (shortened for simplicity):

class MessageView extends React.Component {
  onSend (messages = []) {
    // ...
  }

  render () {
    return (
      <GiftedChat
        messages={this.props.messages}
        onSend={(messages) => this.onSend(messages)}
        user={{ _id: this.props._id }}
      />
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  var msgs = state.inboxReducer.myinbox.find(item =>
    item.owner_id === ownProps.navigation.state.params.owner_id).messages

  msgs = msgs.sort((a, b) => {
    return new Date(a.createdAt) - new Date(b.createdAt)
  })

  return {
    messages: msgs,
    _id: state.user._id
  }
}

export default connect(mapStateToProps, {})(MessageView)

Here's an example of what the messages array looks like(from my initial state):

[{
  _id: 1,
  text: 'Hey whats goin on mate?',
  createdAt: new Date(Date.UTC(2017, 10, 11, 11, 20, 0)),
  user: {
    _id: 1,
    name: 'John Lennon'
  }
},
{
  _id: 2,
  text: 'Just working on the next album.',
  createdAt: new Date(Date.UTC(2017, 10, 11, 11, 25, 0)),
  user: {
    _id: 2,
    name: 'Paul McCartney'
  }
},
{
  _id: 3,
  text: 'Great, I will be in the studio later.',
  createdAt: new Date(Date.UTC(2017, 10, 11, 11, 31, 0)),
  user: {
    _id: 1,
    name: 'John Lennon'
  }
}]

What boggles my mind is that if I put this in the chrome debugging console, the sorting works fine. AND I in fact use the same exact sort in a different React component to get the latest message for the Chat's inbox and this works just fine.

const mapStateToProps = (state) => {
  return {
    inbox: state.inboxReducer.myinbox.map((x) => {
      let msg = x.messages.sort((a, b) => {
        return new Date(a.createdAt) - new Date(b.createdAt)
      }).slice(-1)[0]
      return ({ 
        _id: x._id,
        name: x.name,
        message: msg
      })
    })
  }
}

Has anyone seen a time when an Array.sort() would work in some React contexts but not others?

1
  • 2
    You return messages: newmsgs in the non-working code above. Where does newmsgs come from? Commented Nov 26, 2017 at 2:37

2 Answers 2

4

Try to avoid using new Date() in react native. Instead use libraries such us moment which tackled a lot of problems cause by it. I had similar problem, my sorting worked on simulator but not on device.

//DIDN'T WORK ON DEVICE
const sortedPointsByDate = filteredPoints.sort((a,b)=> new Date(b.logDate) - new Date(a.logDate))

//WORKED ON BOTH
const sortedPointsByDate = filteredPoints.sort((a,b)=> moment(b.logDate) - moment(a.logDate))

I Suggest to try to replace all new Date() instances with moment()

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, man! I can't believe that problem was in date while sorting
3

Always resist the temptation to do sorting or searching on the client/browser, because you will always regret it. Later on you will have more advanced sorting, or for whatever reason you'll end up having to throw it all away. Trust me. If you need information sorted, let the DB do it! Sorry for sounding preachy but that is truly the best answer for you.

4 Comments

Not preachy at all. Very good advice. I will do it that way. Although I'm still baffled by Array.sort working in one method and not another.
@RedOster To troubleshoot that sort (because it's better so indeed solve a mystery like that i guess), you could use JSON.stringify and log the list to the console before and after the sort, to study it that way. I can't remember if it sorts the array 'in place' or if it returns a NEW array sorted, but if you log both to console i bet you figure it out.
@ClayFerguson if you can believe it - now I'm sorting in my controller (main app is a Ruby on Rails web application) and no matter whether I sort it correctly or not on the Rails side it comes incorrectly sorted through React's fetch. Now I gotta figure out where that breakdown is happening.
You should write some code that dumps the list at every stage along the process, so you can see where it looses ordering. It's definitely not loosing sort during the transfer! ha. Mabye you are using some kind of map/collection that is not 'ordered' (map, set, etc).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.