nandorojo / solito

🧍‍♂️ React Native + Next.js, unified.
https://solito.dev
MIT License
3.34k stars 169 forks source link

`useSearchParams` crashing on react native app #472

Open wongk opened 2 months ago

wongk commented 2 months ago

Is there an existing issue for this?

Do you want this issue prioritized?

Current Behavior

I have a component that is rendering as a part of _layout.tsx for a given route. This component uses useSearchParams, which causes the error shown in the attached screenshot. I have logged the value of params from the underling react navigation route, which is what the solito source is referencing, and it is {"screen":"index","params":{}}, which seems quite odd. I am doing this exact same thing from a component that is rendered by index.ts on the same route, and it does not have the same issue. It also works fine in the web app. There does not seem to be a workaround for this.

Expected Behavior

No response

Steps To Reproduce

Call useSearchParams from a component rendered by _layout.tsx.

Versions

- Solito: 4.2.2
- Next.js: 13.5.6
- Expo: 50.0.14
- React Native: 0.73.6

Screenshots

Screenshot 2024-04-25 at 12 47 36 PM

Reproduction

No response

wongk commented 2 months ago

Here is a log from when the route has a query param present: {"initial":true,"screen":"index","params":{"threadId":"965e9694-5747-48b3-85dd-72d617bfbda7"},"path":"/chat?threadId=965e9694-5747-48b3-85dd-72d617bfbda7"}

It appears react navigation is using the params for its own purposes within layout components. Maybe Solito needs to check if params.params is truthy and use that instead?

wongk commented 2 months ago

For anyone else needing a workaround:

function useSafeSearchParams(): ReturnType<typeof useSearchParams> {
  const route = useContext(NavigationRouteContext)
  if (route?.params && Object.hasOwn(route.params, "params")) {
    const realParams = (route.params as any).params
    return useMemo(() => realParams && new URLSearchParams(realParams), [realParams])
  }
  return useSearchParams()
}