Mirrors the functionality of Apollo client's useQuery hook, but with a "query" being any async function rather than GQL statement.

Overview

useAsyncQuery

Mirrors the functionality of Apollo client's useQuery hook, but with a "query" being any async function rather than GQL statement.

Usage

npm i use-async-query

Example usage with Firestore

import firestore from '@firebase/firestore'
import { useQuery } from 'use-async-query'

import { Loading, Error, Results } from './components'

const myQuery = (variables) => firestore()
  .collection('myCollection')
  .where('example', '==', variables.example)
  .get()

const MyComponent = () => {
  const {loading, error, data} = useQuery(myQuery, { variables: { example: 'test' }})

  return <>
    {loading && <Loading />}
    {error && <Error error={error} />}
    {data && <Results data={data}>}
  </>
}
Comments
  • Refetch refetch tests

    Refetch refetch tests

    Some housekeeping:

    • Test naming consistency
    • Merge duplicate describe blocks in tests

    Followed by:

    • Add tests for refetch from a refetch (fixed #52)

    Which resulted in finding and fixing:

    • Refetch from a refetch doesn't trigger rerender (fixed #51)
    opened by penx 2
  • Support double invocation of useMemo useEffect and functional components

    Support double invocation of useMemo useEffect and functional components

    useMemo should not be used for side effects.

    In strict mode during development on React 17, function component bodies and functions passed to useState, useMemo, or useReducer are invoked twice.

    Invocations of a functional component happen before any useEffect within it is resolved. Note that in the following code in React 18, in strict mode, "render" will be logged twice first and then "effect" will be logged twice:

    import { useEffect } from "react";
    
    export default function App() {
      console.log("render");
      useEffect(() => console.log("effect"));
      return null;
    }
    

    https://codesandbox.io/s/use-effect-order-strict-mode-6v00ys?file=/src/App.js:0-152

    (note that in React 17, the console is muted on one of the invocations, which caused me a lot of pain during debugging - this isn't the case in React 18).

    In React 18, functions passed to useEffect are also called twice. I'm not sure if this is dev mode only.

    These are all intentional in order to detect issues e.g. with async react and upcoming features such as preserving state between unmounts.

    We need to set loading=true within the hook depending on whether fetch is going to be called, and then return this value from the hook.

    Perhaps we need to call fetch with useSyncExternalStore (via the separate module for React 17 compatibility) although as we're not caching responses, I don't think we would have an external store, so perhaps this isn't relevant.

    ...or the upcoming useEvent if/when it makes it in to React.

    opened by penx 2
  • Don't call side effects in useMemo

    Don't call side effects in useMemo

    Fixes some strict mode issues during development due to double invoking useMemo

    https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

    Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.

    https://reactjs.org/docs/hooks-reference.html#usememo

    Fixes #47

    Massive thanks to @dai-shi for explaining a few details helping with the final piece of the puzzle (dealing with double invocation of useEffect with a ref)

    https://discord.com/channels/627656437971288081/905738792164556800/977210103847596043

    opened by penx 1
  • Cypress tests

    Cypress tests

    ~@testing-library/react-hooks isn't testing that hooks auto rerender when data change~ (edit:#33), ~nor is it ensuring our types make sense in real world use~ (edit: #34 ).

    => Add some Cypress tests with realistic usage examples

    opened by penx 1
  • Add alternatives to README

    Add alternatives to README

    opened by penx 0
  • Refetch from refetch result does not rerender

    Refetch from refetch result does not rerender

    When calling refetch, you can assign it to a variable:

    const refetchResponse = hookValue.refetch()
    

    This variable allows you to refetch again from the variable rather than from the hook response:

    refetchResponse.refetch()
    

    However, calling refetch in this way does not cause the UI to rerender with a loading state.

    bug 
    opened by penx 0
  • CommonJS Build

    CommonJS Build

    At the moment we only output an ESM build. This is mostly fine with modern tooling but Jest will error and want a CommonJS build.

    https://jestjs.io/docs/ecmascript-modules

    opened by penx 0
  • Why is there an empty catch block?

    Why is there an empty catch block?

    https://github.com/penx/use-async-query/blob/a5c91b7cc19e518d2a9d838491001f6fcf1fc616/use-query.ts#L116-L118

    Perhaps we need to return an error response at this point?

    opened by penx 0
  • Use useLazyQuery without passing initial variables

    Use useLazyQuery without passing initial variables

    At the moment, this:

    export const sendEmail = ({email}: {email: string}) => emailServer.send(email, 'hi');
    
    const useSendEmail = () => useLazyQuery(sendEmail);
    

    Has a type error:

    Argument of type '({ email }: { email: string; }) => Promise<void>' is not assignable to parameter of type '() => Promise<void>'.ts(2345)
    

    Perhaps unrelated but worth exploring, this:

    const useSendEmail = (email: string) =>
      useLazyQuery(sendEmail, {
        variables: {
          email,
        },
      });
    

    ...I think suffers from not being memoized on every call

    opened by penx 0
  • Typed mocks, Reinstate overloads

    Typed mocks, Reinstate overloads

    1. Apply types to Jest mocks. Jest mocks were previously typed to accept and return any, so appropriate type errors were not being thrown
    2. Reinstate overloads to resolve type issues
    opened by penx 0
  • Bugfix - Update after refetch called

    Bugfix - Update after refetch called

    We shouldn't need to call renderHookResult.rerender to get the result from the refetch - the hook should auto update and testing library should update itself.

    opened by penx 0
  • Use useSyncExternalSource instead of refs

    Use useSyncExternalSource instead of refs

    As per @tkdodo advice at

    https://twitter.com/tkdodo/status/1577709398314590213

    Look in to using useSyncExternalSource instead of writing to refs and forcing updates

    opened by penx 0
  • Client from context

    Client from context

    • add a client context provider
    • if context exists when calling hook, pass its value as a client option to the query function
    • if client is specified in options, it overrides anything in context
    enhancement 
    opened by penx 0
  • client Option

    client Option

    Useful if client comes from React context, but you want to define your queries as standalone functions

    https://www.apollographql.com/docs/react/data/queries/#client

    enhancement 
    opened by penx 1
Owner
Alasdair McLeay
React consultant, London/Brighton.
Alasdair McLeay
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
Would You Rather App (Front End Developer Udacity Nanodegree)

Would You Rather App Table of Contents Overview Built with Install (How it works) Overview Would You Rather is the Second project with React Redux in

Ahmed Bayoumi 1 Apr 28, 2022
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.

Recoil · Recoil is an experimental set of utilities for state management with React. Please see the website: https://recoiljs.org Installation The Rec

Facebook Experimental 18.2k Jan 8, 2023
WPPConnect/mobile is an open source project with the objective of automating whatsapp web using the android or ios mobile browser and being able to perform all the functions of our wa-js project

WPPConnect/mobile is an open source project with the objective of automating whatsapp web using the android or ios mobile browser and being able to perform all the functions of our wa-js project, so it is possible to create a customer service, media sending, intelligence recognition based on artificial phrases and many other things, use your imagination to change and modify this project or collaborate on improvements...

null 11 Dec 28, 2022
This repo is for educational and demonstration purposes only, this project is to demonstrate usage of apollo/client and github API and firebase.

Gissues Gissues is a web application that allows you to search for issues in GitHub. It is built for new developers who want to learn more about GitHu

Shikhar 10 Oct 1, 2022
Single function to create, manage, compose variants, for any CSS-in-JS libraries.

Build-variants Single function to create, manage, compose variants, for any CSS-in-JS libraries. Motivation Before diving into the implementation deta

Alexis Mineaud 3 Jan 2, 2023
ESLint plugin for react-hook-form

eslint-plugin-react-hook-form react-hook-form is an awsome library which provide a neat solution for building forms. However, there are many rules for

Chuan-Tse Kao 37 Nov 22, 2022
An extremely helpful React Hook to trap the focusable elements / Hello Modals! Hello a11y!

react-use-focus-trap Everytime when people implement Modals... ...People forget that pro users as well as users that are permanently or temporarily re

David Lorenz 18 Nov 30, 2022
This hook allows you to isolate and manage the state within the component, reducing rendering operations and keeping the source code concise.

React Hook Component State This hook allows you to isolate and manage the state within the component, reducing rendering operations and keeping the so

Yongwoo Jung 2 May 15, 2022
A hook based project created during 20-Dec week ReactJS workshop

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Nabendu 1 Dec 25, 2021
React hook library, ready to use, written in Typescript.

usehooks-ts React hook library, ready to use, written in Typescript. npm i usehooks-ts Created by Julien Caron and maintained with ❤️ by an amazing te

Julien 2.8k Jan 5, 2023
react-dialog is a custom react hook to use a dialog easily

react-dialog react-dialog is a custom react hook to use a dialog easily. Documentation To use react-dialog follow the documentation. useDialog Returns

Levy Mateus Macedo 2 Mar 29, 2022
Small (0.5 Kb) react hook for getting media breakpoints state info in runtime

tiny-use-media Small (0.5 Kb) react hook for getting media breakpoints state info in runtime Usage npm i tiny-use-media --save Adn in your react code

Valeriy Komlev 51 Dec 13, 2022
A reusable react hook that preserves a components semantic accessibility to create a visual block link.

useAccessibleBlockLink is a reusable react hook that preserves a components semantic accessibility to create a visual block link. This hook supports multiple links within the same block.

Wayfair Tech – Incubator 4 Nov 28, 2022
🌐 Unlimited free google translate component & hook

React Native Translator Preview Introduce Free translate component & hook Never need api key, This library is Unlimited free Support translators Googl

Hyun 34 Dec 18, 2022
📋 useClipboardApi() is a React Hook that consumes Web Clipboard API.

?? use-clipboard-api useClipboardApi() is a React Hook that consumes Web Clipboard API. Table of Contents Motivation Usage Contributing Bugs and Suges

Helder B. Berto 22 Dec 15, 2022
A custom react hook to use a dialogs easily.

dialog-hook The dialog-hook is a custom react hook to use a dialog easily. First of all it is necessary to install the package in your project some co

Levy Mateus Macedo 2 Mar 29, 2022
Script to remove unnecessary properties from package.json on prepublish hook

clean-pkg-json Script to remove unnecessary properties from package.json on prepublish hook. Support this project by ⭐️ starring and sharing it. Follo

hiroki osame 37 Oct 16, 2022
An easy hook to use with expo-calendar library!

useCalendar Hook ?? Updated to Expo SDK45 This is an easy hook to use expo-calendar. It allows you: Get access permission to calendar Open settings to

AtilaDev 12 Nov 1, 2022