Skip to content

Commit

Permalink
Add Remix Data APIs (#8937)
Browse files Browse the repository at this point in the history
* feat: add history package and createMemoryHistory implementation (#8702)

* feat: add initial empty history package

* feat: add createMemoryHistory + tests

* chore: add rollup buld for history

* chore: change state type from unknown -> any

* feat: Change listen interface to be pop only

* chore: fix lint warning

* Add history package to yarn workspace

* chore: Address PR feedback

* feat: Add remix-router package and loader functionality

Additional notes:
 - adds unique route id generation to react-router
 - enhances test harness to manage at navigation level
 - combines error/catch into a single exception

* feat: add support for submissions

* chore: code organization + cleanup

* ci: copy over unit test from transition manager

* fix: Fix action arguments bug

* feat: add createBrowserHistory and createHashHistory

* chore: rename package to @remix-run/router

* wip: initial router integration with React

* wip: add userLoaderData

* Remove history package and move history.ts into router

* fix: fix URLSearchParams keys typescript error

This one was tricky:
 - react-router-native used to find the type for URLSearchParams from @types/react-native
 - The new history work added @types/jsdom
 - react-router-native now finds that URLSearchParams before the @types/react-native one
 - the jsdom one imports from the internal built-in TS DOM lib
 - but it does not include the DOM.Iterable values such as keys

See: microsoft/TypeScript#38139

* feat: add data loading/rendering APIs

 - loader/action
 - useLoaderData/useActionData/useTransition
 - exceptionElement/useRouteException
 - fallbackElement

* feat: add browser/hash routers and bring over useSubmit

* feat: bring <Form> to react router-dom

* feat: support redirects returned from loaders

* feat: Support basename in data routers

* chore: remove backup _components file

* chore: extract dom.ts utils file

* feat: add <Route shouldReload> and fix bug in shouldReload logic

* chore: convert to router.subscribe for easier useSyncExternalStore usage

* chore: switch to babel-jest TS transform instead of ts-jest

* fix: make route id optional for backwards compatibility

* feat: default fallbackElement/exceptionElement + add useMacthes/useRouteData

* fix: Fix up build issues with v5-compat

* chore: renames and feedback cleanup

* feat: handle render errors through exceptionElement

* feat: move initial data load into router

* chore: do not handle exceptions for non-data-routers

* chore: remove historyv5 dependency

* feat: add support for router.revalidate()

* feat: add useRevalidator() hook

* fix: fix shouldReload support for revalidate()

* fix: handle 405 action responses correctly

This matches the behavior added to Remix in remix-run/remix#2342

* feat: handle X-Remix-Revalidate hesders returned from loader redirects

This ports over the remix behavior from remix-run/remix#2370

* chore: PR feedback

* chore: copy transition fetcher tests verbatim

* feat: add support for fetchers

* feat: add useFetcher

* ci: add tests for useFetcher/useFetchers

* chore: add formAction to submission

* chore: remove basename from data routers

* chore: change shouldReload url type

* chore: change default fallback element

* chore: add tests for cleanup and make Router type explicit

* feat: support returning responses from loaders/actions

automatically parses the response body with json() or text() depending on the content type of the response. This makes it really convenient to use `fetch` and brings the server semantics to client loaders like `json(data)` or `new Response(“”, { status: 404 })` etc.

* chore: cleanup auto-unwrap logic, add action info to request, remove action submission fields

* feat: provide full control to users in shouldRevalidate

* chore: remove hashchange and create createUrlBasedHistory abstraction

* fix: handle syncronous initial load

* fix request patch

* feat: support fetcher opt-in revalidation

* ci: clean up revalidating fetcher tests and logic

* feat: wiure up useFetcher and turn off revalidation on submit

* docs: update transition/fetcher diagrams

* ci: bump bundle thresholds for new data routing

* chore: update to latest @web-std/fetch with proper formData handling

Our PR was merged and released in 4.1.0 so we can remove our local override.
See: web-std/io#60

* feat: move to better cross-browser fallback spinner

* Revert "feat: move to better cross-browser fallback spinner"

This reverts commit a887019.

* chore: Rename "exception" to "error"

Done in steps via grep/sed:
 - exceptionElement -> errorElement
 - useRouteException -> useRouteError
 - Exception -> Error
 - exceptions -> errors
 - exception -> error

* feat: handle revalidation for interrupted submissions

feat: change defaultShouldRevalidate from funciton -> boolean
chore: simplify revalidation via isRevalidationRequired

* feat: opt-in fetcher.load to revalidation by default

* feat: send actionResult to shouldRevalidate

* feat: add <ScrollRestoration> component and <Link resetScroll=false>

* chore: rename navigation -> transition

* feat: flatten submission onto shouldRevalidate

* feat: simplify form submit logic via event.submitter

Copies the changes from remix remix-run/remix#3094

* chore: clean up types

* chore: sync up react-router-native public api

* feat: properly support React 18 + React.StrictMode

* chore: fix lint warnings

* chore: remove default fallback element

* chore: add @remix-run/router to example vite configs for USE_SOURCE

* chore: add data-router and scroll-restoration examples

* chore: switch from @web-std/fetch to @remix-run/web-fetch for tests

* feat: add pending logic to NavLink (#8875)

* feat: add pending logic to NavLink

* chore: fixup type imports

* chore: add useMemo to nextMatch calculation

* chore: inline react use-sync-external-store/shim for UMD builds

* chore: clean up some exports and add some jsdocs

* feat: add DataStaticRouter for SSR

* chore: fix link

* fix: default replace=false only for GET submissions

* chore: update scroll restoration example to include data loading

* feat: remove fetcher.type since it can be derived

* feat: Remove promise from return signature of router methods

* chore: remove encType from Form props

* WIP docs

* feat: auto-unwrap error Responses into ErrorResponse

* chore: add error boundary example

* feat: support routes prop on data routers

* docs: moar docs

* chore: remove navigation.type

* docs docs docs

* dooooooooooooooooooocs

* docs: fix contributing link (#8885)

* docs: fix contributing link

* chore: add alexlbr to contributors

* Docs: Fix typo in getting-started > concepts (#8888)

* docs: fix small typo in getting-started > concepts

* Sign CLA: add tanayv to contributors.yml

* chore: sort contributors list

* docs: think it’s ready for the big time

* docs: notes demo

* Update overview.md (#8892)

* Update overview.md

* Update contributors.yml

* Version 6.4.0-pre.0

* docs: link fixes

* chore: publish @remix-run/router

* Version 6.4.0-pre.1

* chore: publish @remix-run/router

* Version 6.4.0-pre.2

* docs: DataStaticRouter stub

* docs: not sure what this was 😂

* docs: link to the demo

* fix: properly handle 404s using error boundaries

* docs: getting started installation

* Convert formMethod=GET to be a loading navigation instead of submitting

* Handle invalid GET formData via 400 Bad Request error

* fix: Properly handle descendent routes within a data router

* docs: update useMatches and useNavigation docs

* fix: better solution for 404 error boundaries

* chore: refactor resetScroll to avoid history state mutation

* docs: add note on useMatches and descendent routes

* chore: move newly added resolveTo test from react-router to router

* ci: Remove website workflow before merging remixing work into dev

Co-authored-by: Ryan Florence <rpflorence@gmail.com>
Co-authored-by: Alex Lobera <alex.lobera@gmail.com>
Co-authored-by: Tanay Vardhan <tvardha2@illinois.edu>
Co-authored-by: remix-cla-bot[bot] <92060565+remix-cla-bot[bot]@users.noreply.github.com>
Co-authored-by: Michal Petrik <misopetrik@gmail.com>
  • Loading branch information
6 people committed Jun 6, 2022
1 parent 9d75bfc commit 19d5fa6
Show file tree
Hide file tree
Showing 205 changed files with 29,737 additions and 623 deletions.
31 changes: 0 additions & 31 deletions .github/workflows/website.yml

This file was deleted.

3 changes: 3 additions & 0 deletions contributors.yml
@@ -1,5 +1,6 @@
- abhi-kr-2100
- Ajayff4
- alexlbr
- avipatel97
- awreese
- bhbs
Expand Down Expand Up @@ -54,10 +55,12 @@
- shihanng
- shivamsinghchahar
- theostavrides
- tanayv
- thisiskartik
- ThornWu
- timdorr
- tkindy
- turansky
- underager
- vijaypushkin
- vikingviolinist
307 changes: 307 additions & 0 deletions docs/components/form.md
@@ -0,0 +1,307 @@
---
title: Form
new: true
---

# `<Form>`

The Form component is a wrapper around a plain HTML [form][htmlform] that emulates the browser for client side routing and data mutations. It is _not_ a form validation/state management library like you might be used to in the React ecosystem (for that, we recommend the browser's built in [HTML Form Validation][formvalidation] and data validation on your backend server).

```tsx
import { Form } from "react-router-dom";

function NewEvent() {
return (
<Form method="post" action="/events">
<input type="text" name="title" />
<input type="text" name="description" />
<button type="submit">Create</button>
</Form>
);
}
```

<docs-info>Make sure your inputs have names or else the `FormData` will not include that field's value.</docs-info>

All of this will trigger state updates to any rendered [`useNavigation`][usenavigation] hooks so you can build pending indicators and optimistic UI while the async operations are in-flight.

If the form doesn't _feel_ like navigation, you probably want [`useFetcher`][usefetcher].

## `action`

The url to which the form will be submitted, just like [HTML form action][htmlformaction]. The only difference is the default action. With HTML forms, it defaults to the full URL. With `<Form>`, it defaults to the relative URL of the closest route in context.

Consider the following routes and components:

```jsx
function ProjectsLayout() {
return (
<>
<Form method="post" />
<Outlet />
</>
);
}

function ProjectsPage() {
return <Form method="post" />;
}

<DataBrowserRouter>
<Route
path="/projects"
element={<ProjectsLayout />}
action={ProjectsLayout.action}
>
<Route
path=":projectId"
element={<ProjectPage />}
action={ProjectsPage.action}
/>
</Route>
</DataBrowserRouter>;
```

If the the current URL is `"/projects/123"`, the form inside the child
route, `ProjectsPage`, will have a default action as you might expect: `"/projects/123"`. In this case, where the route is the deepest matching route, both `<Form>` and plain HTML forms have the same result.

But the form inside of `ProjectsLayout` will point to `"/projects"`, not the full URL. In other words, it points to the matching segment of the URL for the route in which the form is rendered.

This helps with portability as well as co-location of forms and their action handlers when if you add some convention around your route modules.

If you need to post to a different route, then add an action prop:

```tsx
<Form action="/projects/new" method="post" />
```

**See also:**

- [Index Search Param][indexsearchparam] (index vs parent route disambiguation)

## `method`

This determines the [HTTP verb](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) to be used. The same as plain HTML [form method][htmlform-method], except it also supports "put", "patch", and "delete" in addition to "get" and "post". The default is "get".

### GET submissions

The default method is "get". Get submissions _will not call an action_. Get submissions are the same as a normal navigation (user clicks a link) except the user gets to supply the search params that go to the URL from the form.

```tsx
<Form method="get" action="/products">
<input
aria-label="search products"
type="text"
name="q"
/>
<button type="submit">Search</button>
</Form>
```

Let's say the user types in "running shoes" and submits the form. React Router emulates the browser and will serialize the form into [URLSearchParams][urlsearchparams] and then navigate the user to `"/products?q=running+shoes"`. It's as if you rendered a `<Link to="/products?q=running+shoes">` as the developer, but instead you let the user supply the query string dynamically.

Your route loader can access these values most conveniently by creating a new [`URL`][url] from the `request.url` and then load the data.

```tsx
<Route
path="/products"
loader={async ({ request }) => {
let url = new URL(request.url);
let searchTerm = url.searchParams.get("q");
return fakeSearchProducts(searchTerm);
}}
/>
```

### Mutation Submissions

All other methods are "mutation submissions", meaning you intend to change something about your data with POST, PUT, PATCH, or DELETE. Note that plain HTML forms only support "post" and "get", we tend to stick to those two as well.

When the user submits the form, React Router will match the `action` to the app's routes and call the `<Route action>` with the serialized [`FormData`][formdata]. When the action completes, all of the loader data on the page will automatically revalidate to keep your UI in sync with your data.

The method will be available on [`request.method`][requestmethod] inside the route action that is called. You can use this to instruct your data abstractions about the intent of the submission.

```tsx
<Route
path="/projects/:id"
element={<Project />}
loader={async ({ params }) => {
return fakeLoadProject(params.id)
}}
action={async ({ request, params }) => {
switch (request.method) {
case "put": {
let formData = await request.formData();
let name = formData.get("projectName");
return fakeUpdateProject(name);
}
case "delete": {
return fakeDeleteProject(params.id);
}
default {
throw new Response("", { status: 405 })
}
}
}}
/>;

function Project() {
let project = useLoaderData();

return (
<>
<Form method="put">
<input
type="text"
name="projectName"
defaultValue={project.name}
/>
<button type="submit">Update Project</button>
</Form>

<Form method="delete">
<button type="submit">Delete Project</button>
</Form>
</>
);
}
```

As you can see, both forms submit to the same route but you can use the `request.method` to branch on what you intend to do. After the actions completes, the `loader` will be revalidated and the UI will automatically synchronize with the new data.

## `replace`

Instructs the form to replace the current entry in the history stack, instead of pushing the new entry.

```tsx
<Form replace />
```

The default behavior is conditional on the form `method`:

- `get` defaults to `false`
- every other method defaults to `true`

We've found with `get` you often want the user to be able to click "back" to see the previous search results/filters, etc. But with the other methods the default is `true` to avoid the "are you sure you want to resubmit the form?" prompt. Note that even if `replace={false}` React Router _will not_ resubmit the form when the back button is clicked and the method is post, put, patch, or delete.

In other words, this is really only useful for GET submissions and you want to avoid the back button showing the previous results.

## `reloadDocument`

Instructs the form to skip React Router and submit the form with the browser's built in behavior.

```tsx
<Form reloadDocument />
```

This is recommended over `<form>` so you can get the benefits of default and relative `action`, but otherwise is the same as a plain HTML form.

Without a framework like [Remix][remix], or your own server handling of posts to routes, this isn't very useful.

See also:

- [`useTransition`][usetransition]
- [`useActionData`][useactiondata]
- [`useSubmit`][usesubmit]

# Examples

TODO: More examples

## Large List Filtering

A common use case for GET submissions is filtering a large list, like ecommerce and travel booking sites.

```tsx
function FilterForm() {
return (
<Form method="get" action="/slc/hotels">
<select name="sort">
<option value="price">Price</option>
<option value="stars">Stars</option>
<option value="distance">Distance</option>
</select>

<fieldset>
<legend>Star Rating</legend>
<label>
<input type="radio" name="stars" value="5" />{" "}
★★★★★
</label>
<label>
<input type="radio" name="stars" value="4" /> ★★★★
</label>
<label>
<input type="radio" name="stars" value="3" /> ★★★
</label>
<label>
<input type="radio" name="stars" value="2" /> ★★
</label>
<label>
<input type="radio" name="stars" value="1" /> ★
</label>
</fieldset>

<fieldset>
<legend>Amenities</legend>
<label>
<input
type="checkbox"
name="amenities"
value="pool"
/>{" "}
Pool
</label>
<label>
<input
type="checkbox"
name="amenities"
value="exercise"
/>{" "}
Exercise Room
</label>
</fieldset>
<button type="submit">Search</button>
</Form>
);
}
```

When the user submits this form, the form will be serialized to the URL with something like this, depending on the user's selections:

```
/slc/hotels?sort=price&stars=4&amenities=pool&amenities=exercise
```

You can access those values from the `request.url`

```tsx
<Route
path="/:city/hotels"
loader={async ({ request }) => {
let url = new URL(request.url);
let sort = url.searchParams.get("sort");
let stars = url.searchParams.get("stars");
let amenities = url.searchParams.getAll("amenities");
return fakeGetHotels({ sort, stars, amenities });
}}
/>
```

**See also:**

- [useSubmit][usesubmit]

[usenavigation]: ../hooks/use-navigation
[formdata]: https://developer.mozilla.org/en-US/docs/Web/API/FormData
[usefetcher]: ../hooks/use-fetcher
[htmlform]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
[htmlformaction]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-action
[htmlform-method]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-method
[urlsearchparams]: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
[url]: https://developer.mozilla.org/en-US/docs/Web/API/URL
[usesubmit]: ../hooks/use-submit
[requestmethod]: https://developer.mozilla.org/en-US/docs/Web/API/Request/method
[remix]: https://remix.run
[formvalidation]: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation
[indexsearchparam]: ../guides/index-search-param
2 changes: 1 addition & 1 deletion docs/components/index.md
@@ -1,4 +1,4 @@
---
title: Components
order: 4
order: 3
---
2 changes: 1 addition & 1 deletion docs/components/link-native.md
@@ -1,5 +1,5 @@
---
title: Link (React Native)
title: Link (RN)
---

# `<Link>` (React Native)
Expand Down

0 comments on commit 19d5fa6

Please sign in to comment.