Here is my observable:
class AppState implements IAppState {
private static instance: AppState;
public static getInstance(): AppState {
if (!AppState.instance) {
AppState.instance = new AppState(AppState.initState);
}
return AppState.instance;
}
static initState: IState = {
isLoading: true,
isSignedIn: false,
};
private appState: IState;
private constructor(state: IState = AppState.initState) {
makeAutoObservable(this);
this.appState = state;
}
set isLoading(isLoading: boolean) {
runInAction(() => (this.appState.isLoading = isLoading));
}
set isSignedIn(isSignedIn: boolean) {
runInAction(() => (this.appState.isSignedIn = isSignedIn));
}
get state() {
return this.appState;
}
}
And here I observe it:
const StackNavigator = observer(() => {
return (
<Stack.Navigator
screenOptions={{
headerShown: false,
gestureEnabled: false,
}}
>
{!AppState.state.isSignedIn ? (
<>
<Stack.Screen name="Login" component={WelcomeScreen} />
<Stack.Screen name="Signup" component={SignUpVM} />
</>
) : (
<>
<Stack.Screen name="Main" component={MainScreen} />
</>
)}
</Stack.Navigator>
);
});
But when AppState.state.isSignedIn
changes the re-render doesn't happen. What could be the reason? May it be connected with the fact I use observable on React Navigation component, not custom one? Any help would be appreciated.
Try changing the order in the constructor:
private constructor(state: IState = AppState.initState) {
this.appState = state;
makeAutoObservable(this);
}
From the docs
make(Auto)Observable only supports properties that are already defined. Make sure your compiler configuration is correct, or as work-around, that a value is assigned to all properties before using make(Auto)Observable. Without correct configuration, fields that are declared but not initialized (like in class X { y; }) will not be picked up correctly.