Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useNavigationParams hook #83

Open
vpontis opened this issue Feb 20, 2020 · 1 comment
Open

useNavigationParams hook #83

vpontis opened this issue Feb 20, 2020 · 1 comment

Comments

@vpontis
Copy link

vpontis commented Feb 20, 2020

We implemented a hook that pulls in the params from the route and optionally clears them when we navigate away from the screen.

This was a common action for us and might be worth pulling into the react-navigation core.

export const useNavigationParams = <T extends object>({
  clearParamsOnBlur = true,
}: {
  clearParamsOnBlur: boolean;
}): T => {
  const [params, setParams] = useState<T>({} as T);
  const route = useRoute<any>();
  const navigation = useNavigation();

  useFocusEffect(
    useCallback(() => {
      if (route.params) {
        setParams(route.params);
      } else {
        setParams({} as T);
      }

      return () => {
        if (clearParamsOnBlur) {
          const nullifiedParams = {} as any;
          Object.keys(route.params || {}).forEach((paramKey) => (nullifiedParams[paramKey] = null));
          navigation.setParams(nullifiedParams);
        }
      };
    }, [route, navigation, clearParamsOnBlur])
  );

  return params;
};

And this is used like:

const Component = () => {
  const { onSuccess } = useNavigationParams({ clearParamsOnBlur: true });
  return (...)
}
@slorber
Copy link
Member

slorber commented Feb 27, 2020

Hi.

Not sure why do you need such a hook. Can you explain? Particularly the part where you do the cleanup.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants