Created
October 17, 2019 23:16
-
-
Save helloncanella/9703497672b11b2879195a71daac7b73 to your computer and use it in GitHub Desktop.
useNewEntries.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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