Coder Social home page Coder Social logo

tanstack / location Goto Github PK

View Code? Open in Web Editor NEW
7.0K 35.0 466.0 11.83 MB

๐Ÿค– Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.

Home Page: https://tanstack.com/router

License: MIT License

TypeScript 98.51% JavaScript 1.49%
react router routing javascript location params searchparams search url route preact solid vue svelte typesafe typescript state-management

location's Introduction

TanStack Router Header

๐Ÿค– Type-safe router w/ built-in caching & URL state management for React, Preact, and friends

#TanStack semantic-release Join the discussion on Github Best of JS

Enjoy this library? Try the entire TanStack! React Query, React Table, React Charts, React Virtual

Visit tanstack.com/router for docs, guides, API and more!

Quick Features

  • 100% TypeSafe
    • Route Defs
    • Navigation
    • Relative Navigation
    • Search Params
    • Path Params
    • Loaders
  • 1st Class Search Params
    • Schemas + Validation
    • Parsing + Serialization
    • Immutable
    • Structural Sharing
    • Pre/Post Processing
  • Built-in Caching
    • Stale-While-Revalidate
    • Max-Age
    • Auto Garbage Collection
    • Invalidation
  • Prefetching
  • Automatic Prefetching
  • Transitions
  • Error Boundaries
  • Code Splitting
  • Layout Routes
  • Easy Integration w/ external caches and storage (eg. React Query, Apollo, SWR, RTKQuery)

Example Usage

To run example React projects with Tanstack Router, see CONTRIBUTING.md

location's People

Contributors

342b45 avatar a89529294 avatar anokthus avatar assone avatar balastrong avatar chorobin avatar coryhouse avatar dependabot[bot] avatar gatorcse avatar giilbert avatar idarklightning avatar judicaelandria avatar jvmusin avatar kurtgokhan avatar lachlancollins avatar mast1999 avatar nklhtv avatar orangeswim avatar ruisaraiva19 avatar ryanstaniforth avatar scarf005 avatar schiller-manuel avatar seancassiere avatar suzan-dev avatar tanner-scadden avatar tannerlinsley avatar tkdodo avatar tordans avatar vafanassieff avatar wesbos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

location's Issues

no way to enforce trailing slash

Describe the bug

A file explorer app

const routes = [
{
    path: '/explorer',
    element: (
      <ExplorerManagerProvider>
        <ExplorerPage />
        <ExplorerReactor />
      </ExplorerManagerProvider>
    ),
    children: [
      {
        path: '*',
        element: <ExplorerFile />,
      },
    ],
  }
]

In ExplorerFile

 const {
    params: { '*': cwd },
 } = useMatch();

Path /explorer will not render ExplorerFile, /explorer/ will render. no way to navigate /explorer to /explorer/

react-location treat /explorer and /explorer/ the same, but router will match different element

Expected behavior

support exact empty match

      {
        path: '',
        element: <Navigate to={'./'} />,
      },

this will error

or how to match no trailing slash in children ? or how to enforce trailing slash ?

Screenshots

image


image


image

throw exception

image

This cause tab cpu load 100%

Desktop (please complete the following information):

  • OS: macos
  • Browser: chrome
  • Version: latest

Additional context

There are cases where `errorElement` is not rendered.

Describe the bug

When loader promise method of the child's route component throws an error,
errorElement will not be rendered.

errorElement is rendered if the match[0].status === 'rejected'.

This match[0] is root component.

https://github.com/tannerlinsley/react-location/blob/62fa0a2396c9a8e8f57932fc7e390d315c0bbc08/packages/react-location/src/index.tsx#L1469

However, child route component also uses loader.
So I want to use the errorElement, when child route component loader is thrown error.

To Reproduce

like this;

    {
      element: <App />,
      loader: async () => {
          await resolvePromise();
      },
      children: [
        {
          path: "/",
          element: <Index />,
          loader: async () => {
             await rejectedPromise();
          },
          errorElement: <ErrorElement />,
        },
        ...

Expected behavior

<ErrorElement /> is rendered when rejectedPromise is thrown error.

Navigate without second parameter

Hi Tanner, many times I just want to navigate to specific route, but there're no need for passing a secondr parameter.

I added a default value to _ref2 on the index.es.js file on function navigate, but I think it's not a "tanner way", so if you can fix it, I'll appreciate it.

Here is my temporary fix
_ref2 = _ref2 || {};

Thanks for this awesome router

Table breaks the UI on mobile view

Describe the bug
The view breaks on mobile screens due to tables (seen at https://react-location.tanstack.com/docs/api screen)

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://react-location.tanstack.com/docs/api
  2. Toggle developer mode and enter mobile responsive view (alternatively just open the url on your mobile phone)

Expected behavior
We can have the table to be a scrollable so that the overall layout doesn't breaks.

Screenshots
image

Desktop (please complete the following information):

  • Windows
  • FIrefox
  • Latest

Smartphone (please complete the following information):

  • Android
  • Brave Browser
  • Latest

Additional context
I can work on fixing this and send a PR

Link component ignore the basepath of LocationProvider

Could it be that you forgot to contemplate it? or maybe I'm missing something to make it work? I tried writing the basepath in all the ways

LocationProvider

<LocationProvider basepath="/subfolder/">
  <App />
</LocationProvider>

Navbar

<nav>
  <Link to="/">Home</Link>
  <Link to="/about-us">About Us</Link>
</nav>

When I click on a link, it goes to the root. The only way to make it work is to write the basepath in the "to" too, but it's not very practical.

Navbar Working

<nav>
  <Link to="/subfolder/">Home</Link>
  <Link to="/subfolder/about-us">About Us</Link>
</nav>

Thanks

Clicking the browserโ€™s back button does not work as expected

Describe the bug
Clicking the browserโ€™s back button does not work as expected.

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://1u4k1.csb.app/
  2. Click Posts link in the page
  3. Click the browserโ€™s back button
  4. The page is still displaying the content of Posts, not the content of the Home page

Expected behavior
display the content of the Home page.

Desktop (please complete the following information):

  • Browser: chrome
  • Version: 96

Additional context
Oddly enough, this is fine in Chromeโ€™s privacy mode or in the Microsoft Edge.

[Kitchen-Sink] Bug with react-location-jsurl

Describe the bug
I'm attracted by this package. But when I try to implement with your kichen-sink, when I change parser to react-location-jsurl, when click to user url become:

http://localhost:3000/dashboard/usersusersView=~%28%29

And of course this route does not exists.

To Reproduce
Steps to reproduce the behavior:

  1. Start kicken sink on Sanbox or localhost
  2. Update custom parser to react-location-jsurl
  3. Click to Dashboard -> User
  4. See error

Expected behavior
There should have a question mask between url and search params like

http://localhost:3000/dashboard/users?usersView=~%28%29

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: MacOS BigSur
  • Browser: Chrome
  • Version: 95

`package.json` specified `module` incorrectly in `react-location-devtools`

Describe the bug
So I use Vite for my React project, and it failed the dev build and manage to find that the module is specified incorrectly in the package.json, or I should say the es module file doesn't seem to get bundled. I can definitely make it works by removing the module field as a workaround

To Reproduce
Steps to reproduce the behavior:

  1. Create a React project via ViteJS
  2. Setup react-location & react-location-devtools
  3. Start the dev server

Expected behavior
The dev server should run just normal.

Screenshots
Screenshot 2021-11-21 at 10 04 52 PM

Desktop (please complete the following information):

  • OS: MacOS
  • Browser: Edge
  • Version: 95.0.1020.53

Smartphone (please complete the following information):

  • Device: -
  • OS: -
  • Browser: -
  • Version:-

Additional context
None

LoaderData cannot be obtained with useMatch in the specific case

Describe the bug
LoaderData cannot be obtained with useMatch in the following cases.

  • Routes with parent-child relationship
  • Data fetch is completed by loader of parent route
  • Data fetch is not completed by loader of child route
  • Using defaultPendingElement
  • defaultPendingMs is longer than the parent data is fetched
  • defaultPendingMs is shorter than the child data is fetched

I want both parent and child to render after all loaders are complete.

If it is difficult, what should I do?

  1. Use ownData
  const {
    ownData: { session }
  } = useMatch<AppLocationGenerics>();
  1. Display pending element if loaderData is empty data
 const {
    data: { session }
  } = useMatch<AppLocationGenerics>();

  if (!session) {
    return <Loading />;
  }
  1. Adjust defaultPendingMs
      defaultPendingMs={1}

To Reproduce
https://codesandbox.io/s/github/ka2jun8/react-location-sample/tree/main/?file=/src/App.tsx

Expected behavior
I want both parent and child to render after all loaders are complete.

Desktop (please complete the following information):

  • OS: macOS
  • Browser: chrome

Additional context

react-location: v3.3.0

Unable to user React Location Devtools with Vite

Unable to use React Location Devtools when using it in React app built with Vite.

Getting following error

Failed to resolve entry for package "react-location-devtools". 
The package may have incorrect main/module/exports specified in its package.json: 
Failed to resolve entry for package "react-location-devtools". The package may have incorrect main/module
/exports specified in its package.json.

Plugin: vite:import-analysis

useNavigate doesn't go to the new url

Describe the bug
When navigating with useNavigate() hook, the page doesn't load the new route unless I manually reload the browser window.

To Reproduce
Inside any app using @tanstack/[email protected]

import {useNavigate} from '@tanstack/react-location';
const navigate = useNavigate();

// Any attempt to trigger navigate from a user action, 
// say a button click like below
navigate({to: '/new-route'})

// the URL in the browser changes
//  but the new location doesn't load.

SSR example does not work

Describe the bug
The SSR example in the API docs does not work as described. It looks like the API for createMemoryHistory is a little different (it expects initialEntries), and there's not clear where loadMatches is coming from in the code example.

Additionally, it seems like the router uses useLayoutEffect, which causes console warnings when trying to SSR.

Extracting an async route with children as a module does not work

Describe the bug
I want to extract an async nested route config to a separate file.

To Reproduce
See the following sandbox for repro.
The sandbox is in a working state where the config is not extracted out. If you comment out the working block and uncomment out the block marked as uncomment where the config is extracted out in ClustersRoute.tsx, it does not work.

Expected behavior
I expect this...

{
  path: "clusters",
  children: [
    {
      path: "/",
      element: () =>
        import("./components/Clusters").then((module) => (
          <module.default />
        ))
    },
    {
      path: `:clusterId`,
      element: () =>
        import("./components/ClusterDetail").then((module) => (
          <module.default />
        ))
    }
  ]
}

to be replaced with

{
  path: "clusters",
  import: () =>
    import("./ClustersRoute").then((module) => module.default)
}

Additional context
react-location: 3.3.0

Note: Extracting an async route works when element is defined at the top level but things under children do not.

useNavigation

On importing useNavigation() an error appear.
The screenshot is provided below.

error

Routes are not matching because of case sensitivity

Describe the bug
Routes seem to default to case sensitive and are not matching if the case is not the same. Is there a way to make them case insensitive by default?

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://wuu8j.csb.app/Posts and you will see that it does not return any results

Expected behavior
I would expect that going to https://wuu8j.csb.app/Posts would return the same result as going to https://wuu8j.csb.app/posts

image

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: I tested using the latest Chrome and FF versions
  • Version: 3.28

Different dynamic route loading with "*" not possible (loader output is cached)

Describe the bug
Sometimes it may be desired/required to have routes defined outside of react-router or the javascript app or they are just not all known to the app. For example asking the backend if it has something to serve for this route.
One of my usecases is content served from an API with thousands of routes, some of which are only available to certain users and deciding which user can access what route is done on-the-fly by the backend.

This use-case can be served by adding a route like this (where fetchRoute performs a request to the backend):

{
	path: "*",
	loader: ({pathname}) => (
		queryClient.getQueryData(["route", pathname]) ?? queryClient.fetchQuery(["route", pathname], () => fetchRoute(pathname))
	),
	element: <RouteComponent />,
}

Unfortunately, a "*" route currently has the same cache key regardless of the pathname, and therefore will fetch the correct content the first route and then return the same content for all following routes.

(Using a route parameter ":foobar" will work for top-level routes, but does not cover n levels of nested routes.)

To Reproduce
I don't think an example is necessary right now, but I'd be happy to create one if needed.

Expected behavior
I think we should consider both the route path "*" aswell as the matched pathname for the cache key and re-run the loader for every pathname.

Workaround
My currently working workaround:

	const loader = React.useCallback(({pathname}) => (
		queryClient.getQueryData(["route", pathname]) ?? queryClient.fetchQuery(["route", pathname], () => fetchRoute(pathname))
	), [])
	const routes = React.useMemo(() => {
		const _routes = []
		const routePaths = ["/"]
		let lastPath = ""
		Array(26).fill().map((element, index) => String.fromCharCode("a".charCodeAt(0) + index)).map(char => {
			lastPath = `${lastPath}/:${char}`
			routePaths.push(`${lastPath}/`)
		})
		routePaths.reverse().forEach((path) => {
			_routes.push({
				loader,
				element: <RouteComponent />,
				path,
			})
		})
		return _routes
	}, [])

This will produce the following 27 routes, all with the same loader and element:

  • /
  • /:a/
  • /:a/:b/
  • /:a/:b/:c/
  • ...
  • /:a/:b/:c/:d/:e/:f/:g/:h/:i/:j/:k/:l/:m/:n/:o/:p/:q/:r/:s/:t/:u/:v/:w/:x/:y/:z/

Some Links on the Website don't work as expected

Hey There, I recently noticed that some of the links don't seem to work on the website.

ok

Clicking on Both Of these opens a link on a new tab but, that link tends to return a 404 error like the below screenshot

404

I think for the API Reference part, the page hasn't been made yet on the website as I've noticed that the page exists on another project like React-Charts.
But, in order to fix docs, the code change should probably be made in this file,
https://github.com/tannerlinsley/react-location/blob/cbc48e4a593651ffd3deb10fa748609804131a7d/docs/src/components/Footer.js

In the above file, <Link href="/overview"> should probably be changed to <Link href="/docs/overview"> redirecting the user to the overview page inside the docs.

DependencyNotFoundError on Kitchen Sink example

react-location-jsurl dependency is missing from the example.

To Reproduce
Steps to reproduce the behavior:

  1. Go to the official react-location website.
  2. See Kitchen Sink example.

Expected behavior
The example should work.

Desktop (please complete the following information):

  • OS: Fedora 34, Linux
  • Browser: Brave

Failed to build with vitejs

Describe the bug
Failed to build with vitejs

Reproduce

import { Outlet, ReactLocation, Route, Router } from "react-location";
import { Home } from "./pages";

const location = new ReactLocation();

const routes: Route[] = [{
  path: "/",
  element: Home,
}];

export default function App() {
  return (
    <div>
      <Router location={location} routes={routes}>
        <Outlet />
      </Router>
    </div>
  );
}

Screenshots
image

Desktop:

  • OS: Windows 10 64bits

__DEV__ global type declaration is included in package

Describe the bug
The global declaration of the const __DEV__ is included in the package types (index.d.ts). This causes issues with my dev environment because I also have a global declaration for this exact variable. I don't think this is necessary or intended to be included. For now I can comment out my own declaration to solve the issue.

To Reproduce
Steps to reproduce the behavior:

  1. Create a declarations.d.ts file
  2. Add declare const __DEV__: boolean;
  3. TypeScript should show an error: Cannot redeclare block-scoped variable '__DEV__'.

Expected behavior
This global development variable should not be included in the distributed package.

Desktop (please complete the following information):

  • OS: Mac OS 10.15.7

Additional context

  • Editor: Visual Studio Code 1.62.1
  • TypeScript: 4.4.4

Issue on "/" paths

Hi Tanner i figured it out that when we have the component like this

<LocationProvider>
    <nav>
      <Link to="/">Home</Link>
      <Link to="dashboard">Dashboard</Link>
      <Link to="invoices">Invoices</Link>
    </nav>
    <div>
      <MatchFirst>
      <Match path="/">
        {console.log('AAA')}
        <div>This is Home</div>
      </Match>
      <Match path="dashboard">
        <div>This is the Dashboard</div>
      </Match>
      <Match path="invoices">
        <MatchFirst>
          <Match path="/">
            {console.log('BBB')}
            <div>Invoices</div>
            <ul>
              <li>
                <Link to="new">New Invoice</Link>
              </li>
              <li>
                <Link to="1">Invoice 1</Link>
              </li>
              <li>
                <Link to="2">Invoice 2</Link>
              </li>
              <li>
                <Link to="3">Invoice 3</Link>
              </li>
            </ul>
          </Match>
          <Match path="new">
            <Link to="..">Back</Link>
            <div>This is a new invoice!</div>
          </Match>
          <Match path=":invoiceID">
            {({ params }) => (
              <div>
                <Link to="..">Back</Link>
                This is invoice #{params.invoiceID}
              </div>
            )}
          </Match>
        </MatchFirst>
      </Match>
      </MatchFirst>
    </div>
  </LocationProvider>

Both console.log execute is like we're missing some exact param or something else.

Broken when using with Vite

Describe the bug
When trying to add the latest version of react-location to a Vite project the routing is not working.

To Reproduce
Steps to reproduce the behavior:

  1. Create new Vite project with the react-ts template
  2. Add react-location as a dependency
  3. Add a simple Router configuration
<Router location={location} routes={[{ path: "/", element: 'test' }]}>
  <Outlet />
  <App />
</Router>
  1. Run yarn dev

Expected behavior
Should show the word "test" on the page.

Screenshots
Screen Shot 2022-02-19 at 8 26 58 AM

Desktop (please complete the following information):

  • OS: macOS
  • Browser: chrome & safari

Additional context
When using the last version (3.3.5) that was not under the @tanstack namespace the app is working without an issue.

Official example does not compile

Describe the bug
Official homepage example does not compile.

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://react-location.tanstack.com/
  2. Scroll down to code
  3. See error

Expected behavior
It compiles.

Screenshots
image

Desktop (please complete the following information):

  • OS: MacOS
  • Browser: Chrome
  • Version: 97

Rendering routes server side with `react-location-lite`

Describe the bug
I've been trying react location lite in an SSR setup and hit a minor hurdle which I think is a bug.

Routes do not render on the server, the <Outlet /> simply renders null and the outlet renders client side. It looks like this is simply a result of this hook not executing on the server:

https://github.com/TanStack/react-location/blob/04abfd6e3b827d818e4444c867092ca93a2e06ee/packages/react-location-lite-experimental/src/index.tsx#L463-L478

It would be necessary to pass the initial path into the ReactLocation instance on the server to make this work, I haven't seen docs on this but something like this is possible:

  new ReactLocation({
    history: createMemoryHistory({
      initialEntries: [new URL(request.url).pathname],
      initialIndex: 0,
    }),
  }),

But I also wonder if there could be a simpler API for this that didn't involve invoking createMemoryHistory manually?

I'm currently just doing something like this in App.tsx to work around the issue:

  const router = useRouter();
  const [initialRoute] = matchRoutes(router, router.state.location);

  return (
    <Suspense fallback={null}>
      {import.meta.env.SSR ? initialRoute.route.element : <Outlet />}
    </Suspense>
  );

I'm wondering if I've missed some obvious pitfall with what I've done, was there a reason this is the SSR behaviour?

Expected behavior
Routes render on the sever and cleaner API for passing the route server side.

Desktop (please complete the following information):

  • OS: mac
  • Browser: chrome
  • Version: 98

Yarn install fails because of dependencies require different "node" versions

Describe the bug
Yarn install fails

To Reproduce
Steps to reproduce the behavior:

  1. Clone repo
  2. Run yarn install
  3. See error, error [email protected]: The engine "node" is incompatible with this module. Expected version "^6.9.0 || ^8.9.0 || ^10.6.0". Got "12.14.1"
  4. Swtich to 10
  5. See error, error @testing-library/[email protected]: The engine "node" is incompatible with this module. Expected version ">=12". Got "10.24.1"
  6. Swtich to 10, go to step 2

Expected behavior
Yarn install install deps without error.

TypeError: Cannot read properties of undefined (reading 'listeners')

Describe the bug
There is an error when jumping the link:

TypeError
Cannot read properties of undefined (reading 'listeners')
notify
https://klup1.csb.app/node_modules/react-location/es/index.js:123:10
eval
https://klup1.csb.app/node_modules/react-location/es/index.js:124:14
ReactLocation.notify
https://klup1.csb.app/node_modules/react-location/es/index.js:123:20

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://react-location.tanstack.com/
  2. Scroll down to the example
  3. Click any link in the example
  4. See error

Expected behavior
expect to navigate correctly

Additional context

Devtools visible in production build

Describe the bug

Currently, the devtools are also displayed in the production build. According to the documentation, they should not be displayed.

Version

"@tanstack/react-location": "^3.6.1",
"@tanstack/react-location-devtools": "^3.4.4",

Expected behavior

Devtools are displayed only in the development environment.

Additional context

Initially, the problem was fixed with commit 5f019c8.

Bug in search params encoding in navigate hook

Describe the bug
The first time I used react-location was version 3.1.0-next.4 with the ReactLocationProvider component. The first thing that got me hooked was the way I could update my search params with the useNavigate hook and retrieve them with the useSearch hook. I could set and retrieve search param without worrying about encoding and decoding.
I upgraded to 3.1.0 a few days ago and found that the useNavigate hook behaviour has changed. Now when I try to set an array search params it is always saved as a string.
The current docs say that JSON.parse and JSON.stringify are used by default to ensure the search params can contain complex objects, but that is currently not the case.

I also tried to provide parseSearch and stringifySearch from react-location-jsurl to ReactLocation but when I try to update my search params it ends up lumping all of the URLs together leading to a 404 page. It doesn't include the ? to differentiate the search params from the root location.

To Reproduce

I created a codesandbox to demonstrate this.
https://codesandbox.io/s/react-location-search-uv1fz

When you click on next you should observe that the JSON object has a string for the after param even though I set it to an array. The expected result (what we have in 3.1.0-next.4) is shown above the actual result.

Additional context

I have been trying for the past two days to decide if this is a bug or an expected behaviour. The docs are not clear if this is the new behaviour.
In case this is the expected behaviour I'd be more than happy to learn how best to proceed and to help update the docs.

Using JSURL as in documentation leads to errors

Describe the bug
When adding JSURL references as explained in doc

import { ReactLocation } from 'react-location'
 import { parseSearch, stringifySearch } from 'react-location-jsurl'
 
 const reactLocation = new ReactLocation({
   parseSearch,
   stringifySearch,
 })

It actually adds the stringifiedSearch without ? making it break the page.

Example
https://codesandbox.io/s/infallible-snowflake-rdq3u?file=/src/index.tsx

To Reproduce
Steps to reproduce the behavior:

  1. Add reference to react-location-jsurl
  2. Add usage of parseSearch, stringifySearch
  3. See the navigation fail

Expected behavior
It should work all the same, as internally I see react-location uses react-location-jsurl, but it seems the API somehow changed.,

Screenshots
If applicable, add screenshots to help explain your problem.
image

Desktop (please complete the following information):

  • OS: Win10
  • Browser: Chrome
  • Version: 95

Search matching routes that only differ in their search function gives duplicate route error

Describe the bug
I'm exploring the capabilities of react-location and am trying to build a stepper using route search matching. I love the idea of being able to define a route for each step based off a search param. However, if doing something like this example below... I get an error saying it's a duplicate route. Which makes sense because not specifying a path defaults to "*", but how is search matching supposed to work if the only thing changing between two routes is the search match?

type LocationGenerics = MakeGenerics<{
  Search: {
    step?: number;
  };
}>;

const routes: Route<LocationGenerics>[] = [
  {
    path: "/stepper",
    element: <StepperContainer />,
    children: [
      {
        search: (search) => {
          return search.step === 0;
        },
        element: <Step1 />,
      },
      {
        search: (search) => {
          return search.step === 1;
        },
        element: <Step2 />,
      },
    ],
  },
];

To Reproduce
Steps to reproduce the behavior:
use the above LocationGenerics and routes in a <Router />

Expected behavior
I'd expect that routes that don't produce the same match based off search matching are treated as separate routes and not as duplicates

Additional context
What's the point of search matching if you can't have routes whose only difference is their search match?

I realize this can be done, by leveraging useSearch within <StepperContainer /> and showing the correct step based off the step param, but I was interested to see if it could be accomplished using search matching in the routes.

`meta` is not returned in `useMatch`

Discussed in #170

Originally posted by vijaypushkin December 22, 2021

Describe the bug

TL;DR; match.route is returned as null from useMatch hook

Main reason for switching from react-router to react-location is to set page title and other meta details right at the routers file.
But for some reason, it is not usable

To Reproduce

const location = new ReactLocation();

const routes = [
  {
    path: '/',
    index: true,
    element: <HomePage />,
    meta: {
      title: () => 'Home',
    },
  },
  {
    path: '/client',
    element: <ClientPage />,
    meta: {
      title: () => 'Client',
    },
   }
 ];
 
 const AppRouter: React.FC = (props) => {
  return (
    <Router location={location} routes={routes}>
      {props.children}
    </Router>
  );
};

Inside HomePage

const match = useMatch();

console.log(match.route?.meta) // returns `null`, match.route is null

Expected behavior

match.route.meta should return meta object set in routes instead of null from useMatch hook

Desktop (please complete the following information):

OS: macOS
Browser: firefox

Additional context
react-location: 3.3.0

Unresolved entry for es package when using Vite

Describe the bug
I installed react-location in my Vitejs app and set up the router exactly as the examples show. When running the dev server, I got an error basically saying it couldn't resolve the entry for react-location

To Reproduce
Steps to reproduce the behavior:

  1. Install react-location in a Vite React App
  2. Setup the router and run the app
  3. This should trigger the error saying it cannot resolve the entry.

Expected behavior
I checked the package.json of react-location and it basically says:

"main": "lib/index.js",
"module": "es/index.js",

It's not resolving because there is no es directory with the entry files in the package when it is installed, when I changed the es to lib it worked fine. I'm going to post in the error that came up below.

Screenshots
If applicable, add screenshots to help explain your problem.

Package folders
react-location-packages@2x

Additional context

> node_modules/vite/dist/node/chunks/dep-be032392.js:30265:10: error: [plugin: vite:dep-scan] Failed to resolve entry for package "react-location". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "react-location". The package may have incorrect main/module/exports specified in its package.json.
    30265 โ”‚     throw new Error(`Failed to resolve entry for package "${id}". ` +
          โ•ต           ^
    at packageEntryFailure (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:30265:11)
    at resolvePackageEntry (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:30261:9)
    at tryNodeResolve (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:30036:11)
    at Context.resolveId (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:29896:28)
    at Object.resolveId (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42356:55)
    at async resolve (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42547:26)
    at async /Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42669:34
    at async callback (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:832:28)
    at async handleRequest (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:664:30)

   node_modules/vite/dist/node/chunks/dep-be032392.js:42659:18: note: This error came from the "onResolve" callback registered here
    42659 โ”‚             build.onResolve({
          โ•ต                   ~~~~~~~~~
    at setup (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42659:19)
    at handlePlugins (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:756:23)
    at Object.buildOrServe (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1044:7)
    at /Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1895:17
    at new Promise (<anonymous>)
    at Object.build (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1894:14)
    at Object.build (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1749:51)
    at /Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42506:54
    at Array.map (<anonymous>)

   src/context/app-context.tsx:1:51: note: The plugin "vite:dep-scan" was triggered by this import
        1 โ”‚ import {ReactLocation, ReactLocationProvider} from 'react-location'
          โ•ต                                                    ~~~~~~~~~~~~~~~~

 > node_modules/vite/dist/node/chunks/dep-be032392.js:30265:10: error: [plugin: vite:dep-scan] Failed to resolve entry for package "react-location". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "react-location". The package may have incorrect main/module/exports specified in its package.json.
    30265 โ”‚     throw new Error(`Failed to resolve entry for package "${id}". ` +
          โ•ต           ^
    at packageEntryFailure (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:30265:11)
    at resolvePackageEntry (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:30261:9)
    at tryNodeResolve (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:30036:11)
    at Context.resolveId (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:29896:28)
    at Object.resolveId (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42356:55)
    at async resolve (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42547:26)
    at async /Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42669:34
    at async callback (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:832:28)
    at async handleRequest (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:664:30)

   node_modules/vite/dist/node/chunks/dep-be032392.js:42659:18: note: This error came from the "onResolve" callback registered here
    42659 โ”‚             build.onResolve({
          โ•ต                   ~~~~~~~~~
    at setup (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42659:19)
    at handlePlugins (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:756:23)
    at Object.buildOrServe (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1044:7)
    at /Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1895:17
    at new Promise (<anonymous>)
    at Object.build (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1894:14)
    at Object.build (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1749:51)
    at /Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/vite/dist/node/chunks/dep-be032392.js:42506:54
    at Array.map (<anonymous>)

   src/unauthenticated-app.tsx:3:31: note: The plugin "vite:dep-scan" was triggered by this import
        3 โ”‚ import {Navigate, Routes} from 'react-location'
          โ•ต                                ~~~~~~~~~~~~~~~~

error when starting dev server:
Error: Build failed with 2 errors:
node_modules/vite/dist/node/chunks/dep-be032392.js:30265:10: error: [plugin: vite:dep-scan] Failed to resolve entry for package "react-location". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "react-location". The package may have incorrect main/module/exports specified in its package.json.
node_modules/vite/dist/node/chunks/dep-be032392.js:30265:10: error: [plugin: vite:dep-scan] Failed to resolve entry for package "react-location". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "react-location". The package may have incorrect main/module/exports specified in its package.json.
    at failureErrorWithLog (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1493:15)
    at /Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1151:28
    at runOnEndCallbacks (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:941:63)
    at buildResponseToResult (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1149:7)
    at /Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:1258:14
    at /Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:629:9
    at handleIncomingPacket (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:726:9)
    at Socket.readFromStdout (/Users/rabahtahraoui/Code/HackPartners/world-app/node_modules/esbuild/lib/main.js:596:7)
    at Socket.emit (node:events:394:28)
    at addChunk (node:internal/streams/readable:315:12)

pendingElement is not being displayed

Describe the bug
Similar to #112 the pendingElement is not being displayed using the async route loader or an async route element.

To Reproduce
Define a route with an async loader or an async element and add a pendingElement.

Expected behavior
The pendingElement should be displayed. Seems to be related to pendingMs. If I add pendingMs: 1 it works.

Desktop (please complete the following information):

  • OS: Windows
  • Browser: Chrome
  • Version: 3.3.0

Nothing is happening after changing search parameters

Describe the bug
Changing search parameters is not triggering navigation, no loader calls.

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/adoring-williamson-9y8e6?file=/src/index.tsx
  2. Click on page 1 link
  3. Click on page 2 link
  4. No new posts from page 2

Expected behavior
New posts from page 2.
This steps are working without issues.

  1. Click on page 1 link
  2. Click on home link
  3. Click on page 2 link
  4. Posts 6-10 are shown

Additional context
This steps are working without issues.

  1. Click on page 1 link
  2. Click on home link
  3. Click on page 2 link
  4. Posts 6-10 are shown

Env:

  • Browser: chrome (latest)
  • Lib version 3.3.0

Can't search through Algolia search bar

Describe the bug
Searching with the Algolia search bar doesn't provide any results

To Reproduce
Steps to reproduce the behavior:

  1. Go to React Location docs landing page
  2. Click on "Search docs" search bar in the header
  3. Try typing any docs related search query
  4. See no results

Expected behavior
Relevant search results present according to the search query entered (or no results message, if non found)

Screenshots
react location landing page docs screenshot with the 403 console error on the side

Desktop (please complete the following information):

  • OS: MacOS Monterey 12.0.1
  • Browser: Firefox 96.0b6
  • Version: 1.0.0

Additional context
This is the error from the console:

{
  "name": "ApiError",
  "message": "Index not allowed with this API key",
  "status": 403
}

Example - Basic with React Query is throwing an error

Describe the bug
Example is crashing with an error

_reactLocation.useIsNextLocation is not a function

To Reproduce
Steps to reproduce the behavior:

  1. Go to Basic with react query example
  2. See the sandbox that loads
  3. See error

Expected behavior
Example should not crash

Screenshots
image

Desktop (please complete the following information):

  • OS: MacOS Big Sur
  • Browser: Firefox, Chrome
  • Version: 94

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser: [e.g. stock browser, safari]
  • Version: [e.g. 22]

Additional context
Add any other context about the problem here.

Kitchen sink [Object object] in urlParams - [Examples]

Describe the bug

When viewing example of "Kitchen sink" the page Dashboard/Users - incorrectly serializes json state.

To Reproduce
Steps to reproduce the behavior:

  1. Go to Dashboard
  2. Click Users
  3. See the url
  4. Modify sort/filters, no effect on url

Expected behavior
The url should be properly serialized,deserialized.

Screenshots
image

Desktop (please complete the following information):

  • OS: Win10
  • Browser: Chrome
  • Version: 95

Additional context
Add any other context about the problem here.

browser entry field in the package.json file is incorrect.

Describe the bug
All the packages have the browser entry field set to build/umd/index.production.min.js but the rollup config is outputting build/umd/index.production.js

The above issue causes a problem when trying to import any package with parcel bundler.

To Reproduce

Expected behavior
Parcel should be able to resolve to correct file specified in the browser entry field.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: mac
  • Browser: chrome
  • Version: [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser: [e.g. stock browser, safari]
  • Version: [e.g. 22]

Additional context
Add any other context about the problem here.

Trailing slash is removed with navigate method

Describe the bug

Even if it specified trailing slash for the next path to with navigate method param, it will be removed.

I understand there is no problem with react-location without trailing slash.
However, there might be cases where a trailing slash is intentionally used because filtering of trailing slash does not work as expected on the infrastructure or backend side, such as a log filtering.

If possible, I want baseSegments.push(toSegment) to be added in the following places, when there is trailing slash.

https://github.com/tannerlinsley/react-location/blob/v3.3.0/packages/react-location/src/index.tsx#L1881

To Reproduce

const navigate = useNavigate();
navigate({ to: "/sample/" });

Expected behavior
Trailing slash remains even after transition.

Desktop (please complete the following information):

  • OS: macOS
  • Browser: chrome

Additional context
react-location: 3.3.0

Component set in the errorElement prop on Route is not being displayed on load error

Describe the bug
the component set in errorElement is not being displayed when an error occurs in the loader function. This also happens with the defaultErrorElement

To Reproduce
Steps to reproduce the behavior:

  1. Go to (https://codesandbox.io/s/gracious-river-qy27x?file=/src/index.tsx:768-777)
  2. Click on the Posts link
  3. See ugly error in sandbox instead of the expected nice error

Expected behavior
I would expect it to render the ErrorTest component in the sandbox. This also fails locally for me

Desktop (please complete the following information):

  • OS: Windows
  • Browser: Chrome
  • Version: 3.28

`useMatch` not able match more than one param

Describe the bug
If my URL contains more than one param like /menu/:menuId/sub/:subId, useMatch will only return menuId when the route is match. I also use useMatchRoute to make sure that the route is really matches.

To Reproduce
Steps to reproduce the behavior:

  1. Create a route that contains two params or more, like /menu/:menuId/sub/:subId
  2. In the corresponding route element, call useMatch
  3. And observe the params that return by useMatch

Expected behavior
The useMatch should return both menuId & subId

Screenshots

Desktop (please complete the following information):

  • OS: MacOS
  • Browser: Microsoft Edge
  • Version: 96.0.1054.43

Website search not working

Describe the bug
Whatever you type in the algolia search box, gets no results

Desktop (please complete the following information):

  • mac
  • chrome

Vite throws 'Uncaught ReferenceError: regeneratorRuntime is not defined'

Describe the bug
Uncaught ReferenceError: regeneratorRuntime is not defined when using react-location with Vite.

To Reproduce
Steps to reproduce the behavior:

  1. yarn create vite --template react-ts
  2. yarn
  3. yarn add @tanstack/react-location
  4. Replace App.tsx with code below
  5. yarn dev
import { ReactLocation, Router } from '@tanstack/react-location';

const location = new ReactLocation();

function App() {
  return (
    <Router location={location} routes={[{ path: '/' }]}>
      <h1>Title</h1>
    </Router>
  );
}

export default App;

Screenshots
Console error

Desktop (please complete the following information):

  • OS: Windows 10 64-bits
  • Browser: Chrome
  • Version: 98.0.4758.102

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.