Skip to content

Instantly share code, notes, and snippets.

@helloncanella
Created October 17, 2019 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helloncanella/9703497672b11b2879195a71daac7b73 to your computer and use it in GitHub Desktop.
Save helloncanella/9703497672b11b2879195a71daac7b73 to your computer and use it in GitHub Desktop.
useNewEntries.js
import _ from "lodash"
import { useState, useEffect, useRef } from "react"
export default function useNewEntries({ entries }) {
const [newEntries, setNewEntries] = useState([])
const oldEntries = useRef(entries)
useEffect(() => {
if (_.isEmpty(entries)) return
const newEntries = entries.filter(entry =>
checkIfEntryIsNew({ entry, oldEntries: oldEntries.current })
)
setNewEntries(newEntries)
oldEntries.current = entries
}, [JSON.stringify(entries)])
return newEntries
}
function checkIfEntryIsNew({ entry, oldEntries }) {
if (_.isEmpty(entry)) return false
const existsAmongOld = (oldEntries || []).some(oldEntry => {
return JSON.stringify(oldEntry) === JSON.stringify(entry)
})
return !existsAmongOld
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment