Reputation: 325
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?
Upvotes: 2
Views: 1575
Reputation: 83
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()
Upvotes: 4
Reputation:
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.
Upvotes: 3