4.0.2 • Published 3 years ago

@respite/action v4.0.2

Weekly downloads
334,637
License
MIT
Repository
github
Last release
3 years ago

@respite/action

A small wrapper around any actioning function that adds some useful metadata.

This will just cover getting started and the api, for an overarching explanation of respite, see the repo readme

Getting started

npm install @respite/core @respite/action

Usage

const {
  action: onSubmit,
  error,
  submitting,
} = useAction(values => post('/api/save', values));

return (
  <button onClick={() => onSubmit(values)} disabled={submitting}>
    Submit
  </div>
);

useAction

(key?: any, callback: Function): {
  action: Function,
  status: Status,
  data: any,
  error: any,
  submitting: boolean,
  reset: () => void,
  invalidate: ({
    key?: any,
    deps?: any[],
    exact?: boolean,
    predicate?: (query: Query) => boolean,
  }) => void,
}

The most common use case is to pair this with @respite/query to invalidate a query upon success:

useAction(async (values) => {
  await post("/api/save", values);

  query.invalidate();
});

If you don't have the query to hand or you have multiple queries, useAction returns a helpful invalidate method:

const { invalidate } = useAction(async (values) => {
  await post("/api/save", values);

  invalidate({ key: "my-query-key" });
});

The key parameter is optional and is only used to drive the @respite/exchange library.

  • action
  • status
  • data
  • error
  • submitting
  • reset Resets status, data, error, and submitting to their original values
  • invalidate Allows you to invalidate queries during the action

useSnapshot

<T>(query: Query<T>): (value: T | (prev: T) => T) => () => void;

Allows you to take a snapshot of a query, update its value, then roll back if required. This is mainly useful for doing optimistic updates during an action:

const setData = useSnapshot(query);

return useAction(async (values) => {
  const rollback = setData((prev) => ({ ...prev, ...values }));

  try {
    await post("/api/save", values);
  } catch {
    rollback();
  }
});
4.0.2

3 years ago

4.0.1

3 years ago

4.0.0

3 years ago

3.0.5

3 years ago

3.0.4

3 years ago

3.0.3

3 years ago

3.0.2

3 years ago

3.0.1

3 years ago

3.0.0

3 years ago

2.8.0

3 years ago

2.7.1

3 years ago

2.7.0

3 years ago

2.6.0

3 years ago

2.5.0

3 years ago

2.5.1

3 years ago

2.2.0

3 years ago

2.4.0

3 years ago

2.1.0

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago