Move onboarding logic into hook/context

I have an onboarding process that requires the user to click a button to acknowledge or dismiss the screens and make it to the regular app.

Currently I have the logic laid out like this, split between my Nav and Onboarding components.

Nav

const [onBoarded, setOnBoarded] = useState(false);

    useEffect(() => {
        const isOnBoarded = async () => {
            const ob = await EncryptedStorage.getItem('ONBOARDED');
            setOnBoarded(!!ob);
        }
        isOnBoarded();
    }, []);

    return (
        <Stack.Navigator
            initialRouteName="onboarding"
        >
            {!onBoarded && <Screen name="onboarding" component={Onboarding} />}
            <Screen name="MainApp" component={MainApp} />
            ...

Onboarding


    const handleOnBoarding = () => {
        EncryptedStorage.setItem('ONBOARDED', 'true');
        navigation.navigate('MainTabNavigator');
    }

   return (
      ...
      <Button onPress={handleOnBoarding}>skip</Button>
      ...
   );

My question is... Is it possible to move this into a hook and keep the same functionality?

I thought it may be possible to do something like

const useOnBoarding = () => {
  const [onBoarded, setOnBoarded] = useState(false);

  useEffect(() => {
    const isOnBoarded = async () => {
      const ob = await EncryptedStorage.getItem('ONBOARDED');
      setOnBoarded(!!ob);
    }
    isOnBoarded();
  }, []);

  const handleOnBoarding = () => {
    EncryptedStorage.setItem('ONBOARDED', 'true');
    setOnBoarded(true);
  }

  return {onBoarded, handleOnBoarding};
}

export default useOnBoarding;

But I can't seem to get it working?


Nav

const {onBoarded} = useOnBoarding();

    return (
        <Stack.Navigator
            initialRouteName="onboarding"
        >
            {!onBoarded && <Screen name="onboarding" component={Onboarding} />}
            <Screen name="MainApp" component={MainApp} />
            ...

Onboarding

 const {handleOnBoarding} = useOnBoarding();

   return (
      ...
      <Button onPress={handleOnBoarding}>skip</Button>
      ...
   );


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation