fix(react): improving lifecycle hooks to deal with stale closures, fixes #19873 (#19874)

This commit is contained in:
Ely Lucas
2019-11-08 16:15:52 -07:00
committed by Liam DeBeasi
parent 0d40d3f3b7
commit 790eb6e15e
3 changed files with 64 additions and 16 deletions

View File

@ -1,31 +1,43 @@
import { useContext, useEffect } from 'react';
import { useContext, useEffect, useRef } from 'react';
import { IonLifeCycleContext } from '../contexts/IonLifeCycleContext';
import { IonLifeCycleContext, LifeCycleCallback } from '../contexts/IonLifeCycleContext';
export const useIonViewWillEnter = (callback: () => void) => {
export const useIonViewWillEnter = (callback: LifeCycleCallback, deps: any[] = []) => {
const context = useContext(IonLifeCycleContext);
const id = useRef<number | undefined>();
id.current = id.current || Math.floor(Math.random() * 1000000);
useEffect(() => {
callback.id = id.current!;
context.onIonViewWillEnter(callback);
}, []);
}, deps);
};
export const useIonViewDidEnter = (callback: () => void) => {
export const useIonViewDidEnter = (callback: LifeCycleCallback, deps: any[] = []) => {
const context = useContext(IonLifeCycleContext);
const id = useRef<number | undefined>();
id.current = id.current || Math.floor(Math.random() * 1000000);
useEffect(() => {
callback.id = id.current!;
context.onIonViewDidEnter(callback);
}, []);
}, deps);
};
export const useIonViewWillLeave = (callback: () => void) => {
export const useIonViewWillLeave = (callback: LifeCycleCallback, deps: any[] = []) => {
const context = useContext(IonLifeCycleContext);
const id = useRef<number | undefined>();
id.current = id.current || Math.floor(Math.random() * 1000000);
useEffect(() => {
callback.id = id.current!;
context.onIonViewWillLeave(callback);
}, []);
}, deps);
};
export const useIonViewDidLeave = (callback: () => void) => {
export const useIonViewDidLeave = (callback: LifeCycleCallback, deps: any[] = []) => {
const context = useContext(IonLifeCycleContext);
const id = useRef<number | undefined>();
id.current = id.current || Math.floor(Math.random() * 1000000);
useEffect(() => {
callback.id = id.current!;
context.onIonViewDidLeave(callback);
}, []);
}, deps);
};