react-ketting
Version:
Ketting bindings for React
73 lines (72 loc) • 2.77 kB
TypeScript
import { State as ResourceState } from 'ketting';
import { ResourceLike } from '../util';
import { UseResourceResponse } from './use-resource';
export declare type UseNewResourceOptions<T> = {
initialState: ResourceState<T>;
refreshOnStale?: boolean;
} | {
initialData: T;
refreshOnStale?: boolean;
};
/**
* useNewResource is a hook that helps you create new resources on a typical
* REST api.
*
* This hook is for a specific use-case in React application; use this hook
* if you want to present the user a form to create the resource, and after
* creation the user *stays* on that form and continues editing after
* creation.
*
* If you're just looking for a way to do a POST request and redirect/refresh
* the interface, don't use this hook. Instead, you probably just want to call
* `someResource.postFollow()` in an event handler and do something specific
* after it was successful.
*
* A general guideline of when this component is useful is if 'creating'
* and 'editing' is continuous and not really discernable from a UX
* perspective.
*
* The assumptions this hooks makes:
*
* 1. You create new resources with POST requests.
* 2. The body of the POST request is the same (or similar enough) to the
* body of the resource you're eventually creating.
* 3. The server returns a 201 Created status code when successful.
* 4. The server also returns a Location header referring to the new resource.
* 5. After creation, any changes the user makes result in a `PUT` request to
* the new location.
*
* Example call:
*
* <pre>
* const {
* error,
* resourceState,
* setResourceState,
* submit
* } = useNewResource(targetResource, { initialData: { foo: bar });
* </pre>
*
* You must pass some 'initial data' to this function that's used to
* initialize the data object. Think of this as the 'template' or starting
* value.
*
* Instead of 'initialData', you may also pass 'initialState', which requires
* a fully fledged 'State' object.
*
*
* Returned properties:
*
* * error - Will be null or an error object.
* * resourceState - A state object. The `.data` property of this object will
* contain the parsed JSON from the server.
* * setResourceState - Update the local cache of the resource.
* * submit - When called the first time, sends a POST request to the
* collection/target resource. The second time it will send a PUT
* request to the previously created resource.
* </pre>
*
* To do POST requests you must specifiy initialState with the state the user starts
* off with.
*/
export declare function useNewResource<T>(targetResource: ResourceLike<any> | string, options: UseNewResourceOptions<T>): UseResourceResponse<T>;