In module 4 of the React course, there’s a challenge to sort the notes by the most recently updated note to the least recently updated note. In the challenge it’s said that we don’t need to save the sorting in state and then in the solution it’s created the following const:
const sortedNotes = notes.sort((a, b) => b.updatedAt - a.updatedAt)
and that const is passed as props in the sidebar component
My question is if we couldn’t just put the sort function inside snapshot like this
React.useEffect(() => {
const unsubscribe = onSnapshot(notesCollection, function(snapshot) {
// Sync up our local notes array with the snapshot data
const notesArr = snapshot.docs.map(doc => ({
…doc.data(),
id: doc.id
}))
// Sort the array by the updatedAt
field, from newest to oldest
notesArr.sort((a, b) => b.updatedAt - a.updatedAt)
setNotes(notesArr)
})
return unsubscribe
}, )
I kow that this saves the changes into state, but isn’t it more simple and effective?