The "shared query" is a data fetching convenience library that helps users
to load data, check for staleness and expiration, cache in memory, local
storage or indexed db, and be able to manipulate the data anytime.
Each shared query creates a new private shared state that handles the data
storage. This shared state contains the records for all queries, where each
query is a unique set of arguments used to make the query. The number of
records and the total byte size of data can be limited so as to ensure the
query does not take up too much memory.
// Create a new shared query in the top level scope. // The query function `queryFn` here does not take any arguments. // // Only the queryName and queryFn are required and everything else is // optional. // // The queryName must be unique, otherwise we will throw an // error. This is because defining the same queryName for two different // queries implies that the queries are the same, thus violating the idea // of a "shared" query, and almost certainly points to a bug in the code. exportconstusersQuery = sharedQuery({ queryName:"users", queryFn:listUsers, persistTo:"indexedDb", staleMs:MS_PER_DAY, });
// Note that the query will only start fetching on mount in React. // But you can do `usersQuery.getCachedOrFetch()` here to prefetch the // data if necessary. usersQuery.getCachedOrFetch();
// Example of using a query function with arguments. exportconstgetUserQuery = sharedQuery({ queryName:"getUser", queryFn:getUser, // getUser(userId: string) => User persistTo:"indexedDb", staleMs:MS_PER_DAY, });
exportconstUsersComponent: React.FC = () => { // Second argument is optional, and is an array of arguments to be // passed to the `queryFn`. constusers = useSharedQuery(usersQuery);
exportconstAnotherComponent: React.FC = () => { // This query will be deduped with the one above, sharing the same // data and the same fetches. constusers = useSharedQuery(usersQuery); ... };
exportconstDisplayOneUser: React.FC<{userId: string}> = ({userId}) => { // Example of using the query with an argument. Whenever the argument // changes, the data will be fetched and updated automatically. constuser = useSharedQuery(getUserQuery, [userId]);
The "shared query" is a data fetching convenience library that helps users to load data, check for staleness and expiration, cache in memory, local storage or indexed db, and be able to manipulate the data anytime.
Each shared query creates a new private shared state that handles the data storage. This shared state contains the records for all queries, where each query is a unique set of arguments used to make the query. The number of records and the total byte size of data can be limited so as to ensure the query does not take up too much memory.
Example: