Reputation: 87
I encountered an issue with React Native with Expo when styling React Native Paper that I'm trying to understand.
I created a code sample with the issue: https://gitlab.com/mszymczakowski/react-native-paper-theming-issue
When I export the const with custom theme from App.tsx
file, then import and try to use it in HomeScreen.tsx
I'm getting a type error undefined is not an object (evaluating '_App.customTheme.colors')
.
Moving the const with custom theme to another .ts
file seems to fix the issue - I can use it both in App.tsx
and HomeScreen.tsx
: https://gitlab.com/mszymczakowski/react-native-paper-theming-issue/-/tree/theme-fix
But as I mentioned I'd like to understand what's happening here and why there's an error in one approach but not in second one.
Thanks in advance
Upvotes: 0
Views: 1133
Reputation: 116
This is not strictly about react-native neither react-native-paper, but javascript (ES2015) import(s).
When module A imports module B, in order to execute module A, it's executed firstly 'module B', otherwise executing module A you could get errors of 'undefined' (objects, etc.) because it could try to use something that should be exported from module B.
In your case module in 'App.tsx' imports module in 'HomeScreen.tsx', so the runtime tries to execute before HomeScreen and then App, BUT in HomeScreen you imported something (customTheme) from the same module 'App.tsx', generating what could be called a "require cycle".
Note
Actually if I try to run your sample project I get (before the error: undefined is not an object) a warning: "Require cycle: App.js -> src/screens/HomeScreen.js -> App.js" followed by warning message "Require cycles are allowed, but can result in uninitialized values." and I think you too got this warning.
What's happened? The runtime executes firstly HomeScreen and when tries to access customTheme property (line 21) it throws 'undefined is not an object' error because in that moment App module is not yet executed and then customTheme is not yet initialized.
What's different in second approach?
In order to execute App.tsx, firstly it's executed HomeScreen.tsx, and in order to execute HomeScreen.tsx, firstly it's executed Theme.tsx so that actually the "order of execution" is:
Theme.tsx => HomeScreen.tsx => App.tsx
Upvotes: 1