Skip to content
This repository was archived by the owner on Aug 8, 2024. It is now read-only.
This repository was archived by the owner on Aug 8, 2024. It is now read-only.

useNavigationParams hook #83

@vpontis

Description

@vpontis

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 (...)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions