|
| 1 | +--- |
| 2 | +"react-router-dom": minor |
| 3 | +--- |
| 4 | + |
| 5 | +Add support for `application/json` and `text/plain` encodings for `useSubmit`/`fetcher.submit`. To reflect these additional types, `useNavigation`/`useFetcher` now also contain `navigation.json`/`navigation.text` and `fetcher.json`/`fetcher.text` which are getter functions mimicking `request.json` and `request.text`. Just as a `Request` does, if you access one of these methods for the incorrect encoding type, it will throw an Error (i.e. accessing `navigation.formData` when `navigation.formEncType` is `application/json`). |
| 6 | + |
| 7 | +```jsx |
| 8 | +// The default behavior will still serialize as FormData |
| 9 | +function Component() { |
| 10 | + let navigation = useNavigation(); |
| 11 | + let submit = useSubmit(); |
| 12 | + submit({ key: "value" }); |
| 13 | + // navigation.formEncType => "application/x-www-form-urlencoded" |
| 14 | + // navigation.formData => FormData instance |
| 15 | + // navigation.text => "key=value" |
| 16 | +} |
| 17 | + |
| 18 | +function action({ request }) { |
| 19 | + // request.headers.get("Content-Type") => "application/x-www-form-urlencoded" |
| 20 | + // request.formData => FormData instance |
| 21 | + // request.text => "key=value" |
| 22 | +} |
| 23 | +``` |
| 24 | + |
| 25 | +```js |
| 26 | +// Opt-into JSON encoding with `encType: "application/json"` |
| 27 | +function Component() { |
| 28 | + let submit = useSubmit(); |
| 29 | + submit({ key: "value" }, { encType: "application/json" }); |
| 30 | + // navigation.formEncType => "application/json" |
| 31 | + // navigation.json => { key: "value" } |
| 32 | + // navigation.text => '{"key":"value"}' |
| 33 | +} |
| 34 | + |
| 35 | +function action({ request }) { |
| 36 | + // request.headers.get("Content-Type") => "application/json" |
| 37 | + // request.json => { key: "value" } |
| 38 | + // request.text => '{"key":"value"}' |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +```js |
| 43 | +// Opt-into JSON encoding with `encType: "application/json"` |
| 44 | +function Component() { |
| 45 | + let submit = useSubmit(); |
| 46 | + submit("Text submission", { encType: "text/plain" }); |
| 47 | + // navigation.formEncType => "text/plain" |
| 48 | + // navigation.text => "Text submission" |
| 49 | +} |
| 50 | + |
| 51 | +function action({ request }) { |
| 52 | + // request.headers.get("Content-Type") => "text/plain" |
| 53 | + // request.text => "Text submission" |
| 54 | +} |
| 55 | +``` |
0 commit comments