ahmetarslan
ahmetarslan

Reputation: 11

Expo Router - Error unable to call provider in layout file

_layout.tsx

import FontWrapper from "@/wrappers/font-wrapper";
import { ThemeProvider } from "@/wrappers/theme-wrapper";
import Root from "./root";

const StackLayout = () => {
  return (
    <FontWrapper>
      <ThemeProvider>
        <Root />
      </ThemeProvider>
    </FontWrapper>
  );
};

export default StackLayout;

root.tsx

import { Stack } from "expo-router";

const Root = () => {
  return (
    <Stack
      screenOptions={{
        headerShown: false,
      }}
    >
      <Stack.Screen name="index" />
      <Stack.Screen name="login" />
      <Stack.Screen name="tabs" />
      <Stack.Screen
        name="bid/detail"
        options={{ animation: "slide_from_bottom" }}
      />
      <Stack.Screen
        name="modals/imageViewer"
        options={{ presentation: "modal", animation: "slide_from_bottom" }}
      />
    </Stack>
  );
};

export default Root;

ERROR [Error: Attempted to navigate before mounting the Root Layout component. Ensure the Root Layout component is rendering a Slot, or other navigator on the first render.]

I am using the latest versions of expo router v2 and expo sdk 49. I was not having any problems with the expo router. I get this problem when I call provider in my _layout file, where should I use my providers?

I called my providers in my index.js file, but I could not access my providers from within the application.

Upvotes: 0

Views: 2402

Answers (2)

Aaron Saunders
Aaron Saunders

Reputation: 33345

const navigationState = useRootNavigationState();
if (!navigationState?.key) return;

If you don't have a key, then router is not ready and app will fail:

https://github.com/expo/router/issues/740

Upvotes: 1

user22253948
user22253948

Reputation: 1

Warning - Am a RN & SO newbie. Sharing in the hope you may find some use here. Apologies if I am completely off here.

I was struggling with a similar issue today. Seems like that in Expo Router V2, the RootLayout needs to render a Stack or Slot etc. If you try to do any rendering before that it results in an error. In your code, you are going even beyond that & trying to wrap the Root Layout itself inside another component. So that won't work. Just move the Providers that you have in the StackLayout inside Root. Below code worked for me. I also think this issue - https://github.com/expo/router/issues/430 - is related.

export default function RootLayout () {
// any other code you need here
return (
<ThemeProvider value={DefaultTheme}>
  <Stack>
    <Stack.Screen name="login" options={{ headerShown: true }} />
    <Stack.Screen name="screen2" options={{ headerShown: true }} />
  </Stack>
</ThemeProvider>
)
}

Upvotes: 0

Related Questions