Skip to content

Expo Router Adapter / CJS Support #837

Open
@izakfilmalter

Description

@izakfilmalter

I have stubbed out an adapter that would work for Expo Router:

import { Array, Option, pipe, Record } from 'effect'
import { router, type UnknownOutputParams, useGlobalSearchParams, useSegments } from 'expo-router'
import {
  type unstable_AdapterInterface,
  unstable_createAdapterProvider,
} from 'nuqs/dist/adapters/custom'

export function useGlobalQueryParams<TParams extends UnknownOutputParams = UnknownOutputParams>() {
  const params = useGlobalSearchParams<TParams>()
  const segments = useSegments()
  const urlParams = segments
    .filter((segment) => segment.startsWith('[') && segment.endsWith(']'))
    .map((segment) => segment.slice(1, -1))

  return Object.fromEntries(
    Object.entries(params).filter(([key]) => !urlParams.includes(key)),
  ) as TParams
}

function useNuqsExpoRouterAdapter(): unstable_AdapterInterface {
  const params = useGlobalQueryParams<Record<string, string>>()

  const updateUrl = (searchParams: URLSearchParams) => {
    const newParams = Object.entries(Object.fromEntries(searchParams))
    const oldParams = pipe(params, Record.toEntries)

    const paramsToRemove = pipe(
      oldParams,
      Array.filter(([oldKey]) =>
        pipe(
          newParams,
          Array.findFirst(([newKey]) => oldKey === newKey),
          Option.isNone,
        ),
      ),
      Array.map(([key]) => [key, undefined]),
    )

    router.setParams({
      ...Object.fromEntries(paramsToRemove),
      ...Object.fromEntries(newParams),
    })
  }

  return {
    searchParams: new URLSearchParams(params),
    updateUrl,
    rateLimitFactor: 2,
    getSearchParamsSnapshot: () => new URLSearchParams(params),
  }
}

export const NuqsExpoAdapter = unstable_createAdapterProvider(useNuqsExpoRouterAdapter)

The problem I am running into is expo uses the metro bundler. Metro doesn't support ESM yet, so everything has to be CJS. Is there away we can add CJS support back to this package?

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions