I'm trying to conditionally render my redux app based on if the user is logged in. The relevant & condensed version of my code is below:
let isLoggedIn = false;
export default function App() {
console.log('App executing...');
console.log('isLoggedIn: ', isLoggedIn);
return (
<Provider store={store}>
<NavigationContainer>
{isLoggedIn ? ContactsTab() : Login()}
</NavigationContainer>
</Provider>
);
}
store.subscribe(() => {
// Set isLoggedIn to true if token is received and reinvoke App()
if (store.getState().user.token) {
isLoggedIn = true;
App();
}
});
The app starts with console logging isLoggedIn: false and displaying Login()(as expected). When I login on my phone using the correct credentials, App() is re-invoked console logging isLoggedIn: true(as expected) but it's still displaying Login(). If I set isLoggedIn = true inside the app function, the app successfully starts displaying the ContactsTab().
What is happening here? Why is my app not moving to ContactsTab() when the value of isLoggedIn successfully changes to true? How can I fix this?
Thank you for reading along. I have been trying to debug this for the past 2 days with no success so any help would be greatly appreciated!
You need to use useState here like this, the useState will automatically renders when the state changes
export default function App() {
const [isLoggedIn, setLoggedIn] = useState(false);
console.log('App Executing...');
console.log('isLoggedIn: ', isLoggedIn);
store.subscribe(() => {
// Set isLoggedIn to true if token is received and reinvoke App()
if (store.getState().user.token) {
setLoggedIn(true);
}
});
return (
<Provider store={store}>
<NavigationContainer>
{isLoggedIn ? ContactsTab() : Login()}
</NavigationContainer>
</Provider>
);
}
Hope this helps!