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?
messages: newmsgsin the non-working code above. Where doesnewmsgscome from?