I have a nextjs application. There is a page that has a list of documents. If someone uploads a document, the list gets one item added. The task is, if someone moves out of the page and if the list still have some items, we need to call one API for each documents. How can it do it in react and nextjs?
export const Page = () => {
const [documents, setDocuments] = useState([]);
const deleteDocuments = useCallback(() => {
documents.forEach(d => deleteFunction)
}, [deleteFunction, documents]);
useEffect(() => {
return () => deleteDocuments()
}, [deleteDocuments] );
return "...some..html.."
}
We are using useEffect
‘s cleanup function to handle that.
But, the issue is, since the delete function is used, it is part of useEffect
dependency and since that function depends on documents
, it is part of dependency function. Due to this, anytime user adds a document inside documents array, the useEffect’s cleanup function is called because array is changed.
I want this function to be called only once on page leave. (it is okay if it is being called two times initially for react strict mode)
There are two ways we potentially can fix
First
We can omit the dependency for delete function
const deleteDocuments = useCallback(() => {
documents.forEach(d => deleteFunction)
}, [deleteFunction]); // <-- remove documents from the list
useEffect(() => {
return () => deleteDocuments()
}, [deleteDocuments] );
I am not a fan of this approach because we never know when this thing starts failing because of unhandled dependency
Second
To use useRef
const [documents, setDocuments] = useState([]);
const documentsRef = useRef(documents);
useEffect(() => {
documentsRef.current = documents;
}, [documents]);
const deleteDocuments = useCallback(() => {
documentsRef.current.forEach(d => deleteFunction)
}, [deleteFunction]); // <- no need to have documents or documentRef as dependency
useEffect(() => {
return () => deleteDocuments()
}, [deleteDocuments] );
If we maintain the documentRef
, we don’t need to maintain that in the dependency array.
However, I am not sure if this is the best approach. Because React suggest to not to fall for the pitfall of using useRef. However, the example they suggested make sense for them because it would connect and close connection but our example is not prone to that bug because as soon as something is rendered, the document array would be [] and it does not matter if the delete document function is called two time for an empty array.
Anything better?
Is there a better solution to tackle this?
PS
I understand that, I haven’t added window.beforeunload
event. I ommitted that for simplicity in example, but I am planning to have it in actual production code.