Skip to content

Commit

Permalink
Move navigation to machine
Browse files Browse the repository at this point in the history
  • Loading branch information
g-todorov committed May 14, 2024
1 parent 9cd7bfa commit ea1734d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
23 changes: 21 additions & 2 deletions src/machines/authenticated.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { ActorRefFrom, setup, assign } from "xstate";
import { ActorRefFrom, setup, assign, fromCallback } from "xstate";
import { AuthenticatedParamList } from "../types/navigation";
import { HomeMachineActor, homeMachine } from "./home";
import { ListMachineActor, listMachine } from "./list";
import {
getCurrentRouteName,
navigationRef,
} from "../navigation/NavigationRef";

export type AuthenticatedMachineActor = ActorRefFrom<
typeof authenticatedMachine
Expand All @@ -27,7 +31,21 @@ export const authenticatedMachine = setup({
},
}),
},
actors: { homeMachine, listMachine },
actors: {
homeMachine,
listMachine,
navigationSubscriber: fromCallback(({ sendBack }) => {
const unsubscribe = navigationRef.addListener("state", (_event) => {
const screenRoute = getCurrentRouteName();

if (screenRoute) {
sendBack({ type: "NAVIGATE", screen: screenRoute });
}
});

return unsubscribe;
}),
},
guards: {
isHomeScreen(_, params: { screen: keyof AuthenticatedParamList }) {
return params.screen === "Home";
Expand All @@ -40,6 +58,7 @@ export const authenticatedMachine = setup({
context: { refHome: undefined, refList: undefined },
id: "application",
initial: "homeScreen",
invoke: { src: "navigationSubscriber" },
on: {
NAVIGATE: [
{
Expand Down
5 changes: 0 additions & 5 deletions src/navigation/AuthenticatedNavigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
import { AuthenticatedMachineActor } from "../machines/authenticated";
import HomeScreen from "../screens/Home";
import ListScreen from "../screens/List";
import { useNavigator } from "../hooks/useNavigator";

const Stack = createNativeStackNavigator<AuthenticatedParamList>();

Expand All @@ -22,10 +21,6 @@ export function AuthenticatedNavigator({ actorRef }: Props) {
return snapshot;
});

useNavigator<AuthenticatedParamList>((route) => {
actorRef.send({ type: "NAVIGATE", screen: route });
});

return (
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home">
Expand Down

0 comments on commit ea1734d

Please sign in to comment.