Giter Club home page Giter Club logo

graphql-hooks's Issues

Inconsistent results for changing query

Package

graphql-hooks

Environment

  • graphql-hooks version: 3.4.0
  • react version: 16.8.4
  • Browser: Any

Description

When a query changes quickly results are inconsistent. What's wrong is that the current query is not tracked inside useClientRequest.js resulting in a race between different queries and the last one will be stored in state. In my case having consistent timing of server that means if I click next multiple times, I will see loading state at first and then multiple UI updates. Also, the loading state is lost since there's some of the old data in the state which arrived after all loading actions have been dispatched.

How to reproduce

I created a simple code sandbox where you can click next/prev multiple times and see the issue in action.
https://codesandbox.io/s/mj6m8yvv4p

Suggested solution (optional)

If this is undesired behavior I would like to open a PR solving that.

Requests are not cancelled on unmount

Environment

  • graphql-hooks version: 3.1.0
  • react version: 16.8.3
  • Browser: Any

Description

Requests are not cancelled on unmount which means we try to update state after component is gone.

screenshot 2019-02-25 at 14 51 44

How to reproduce

Can be reproduced in the example next app by simulating slow connections and upvoting a post, then navigating to the about page before the request returns.

Suggested solution (optional)

Keep track of whether the component is mounted by making useClientRequest return a method to cancel everything. This would switch an internal var that we would check once the request has returned, so that we don't then try to set state.

Discuss, Slack...Discord channel :D

Maybe some tool to spread love, this library is great and I think will have future, please make some chat around :)

Also, somebody has a NextJs boilerplate to share with graphql-hooks :v ?
Thanks guys, you're doing a great thing here.

Local set up included in contributing guidelines/getting started

Description

For a fresh contributor there are no guidelines on how to set up the project in order to develop against it. This may be related to #40.

On a fresh clone, being able to jump straight into development would be ideal 👍

Suggested implementation

Extra information included in the CONTRIBUTING.md file either pointing at starter apps or with instructions on how to set up as a monorepo?

Test fetchData from useClientRequest

See

it.skip('needs testing', () => {
// fetchData updates the state & therefore needs to be wrapped inside an `act`
// https://reactjs.org/docs/test-utils.html#act.
//
// Warning: An update to TestHook inside a test was not wrapped in act(...).
// When testing, code that causes React state updates should be wrapped into act(...):
// act(() => {
// /* fire events that update state */
// });
// / * assert on the output */
// This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
// in TestHook
// in Wrapper
//
// fetchData is an async function, which `act` does not currently support
// see https://github.com/facebook/react/issues/14769
//
// support is currently being implemented
// see https://github.com/facebook/react/pull/14853

Add ability to skip query entirely

Description

In some cases one could skip making the request to graphql if some condition is true. For example if you have two cascade dropdowns on initial render you want to load and display data only in the first one and the second one just display it as disabled. When you pick something in the first dropdown you have to query the data for the second dropdown.

In this example the second dropdown will skip making the request to get the data until the condition to have selected some value in the first dropdown is met.

Suggested implementation

A skip boolean prop could be set as part of useQuery opts and if true the entire query will be skipped and it will return data as undefined

useManualQuery returns state.loading=true by default

Package

graphql-hooks

Environment

  • graphql-hooks version: 3.3.1

Description

Calling useManualQuery currently returns a state with loading set to true, even though the request function has not been called.

How to reproduce

  • Call useManualQuery
  • Inspect state

Add an example for graphql upload mutation example.

I'm hoping it's possible to upload file to a server using graphql-hooks (form-data). If it's not how are you guys achieving file upload with graphql?
Can anyone add an example of upload mutation with graphql-hooks? Thanks

Running tests yields errors

Environment

  • graphql-hooks version: 3.1.1
  • react version: 16.8.3
  • Browser: N/A

Description

Running npm run test yields several errors although the tests pass.

Warning: An update to TestHook inside a test was not wrapped in act(...).

      When testing, code that causes React state updates should be wrapped into act(...):

      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

      This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act

I believe the errors are printed when running useQuery.test.js and useClientRequest.test.js.

How to reproduce

npm run test

Suggested solution (optional)

  • Potential versioning issue?

Add useDebugValue

Description

I would like this package to add useDebugValue to hooks and make them simple to track in dev tools. I think just showing Loading/Loaded/Error would be enough for useQuery to give a user a sense of what's going on with a hook. Current implementation gives out a few nested hooks without showing relevant data (that's how dev tools are with complex data), so just showing a status would be an improvement.

Suggested implementation

I can implement that upon discussion and send a PR.

Add ability to require GraphQLClient without having React in scope

Description

Even though the library is about React hooks, it provides a generic GraphQL client that doesn't really need React to work.

Because of the way the modules are bundled, it's currently not possible to require the GraphQLClient module alone, meaning that you have to import the whole module bundle, hence creating a dependency on React.

Suggested implementation

Change the rollup configuration so that it outputs not just a single output module, but one for the GraphQLClient as well, so that it can be required as a standalone module.

Add end to end tests

Package

All packages

Description

Add end to end test using one of the example apps. We've been using testcafe on other projects with some success, it should be fairly straight forward to set that up.

It would be great if we could, as part of a PR, build and deploy an example app and then run the tests against it.

If we used the next.js example(would require bringing in to this repo), then we could use now.sh and it's github pull request feature. The other option is using Heroku's review apps with any of our examples.

Add unit tests

Add unit test coverage for all files, there are currently none

---------------------|----------|----------|----------|----------|-------------------|
File                 |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------------|----------|----------|----------|----------|-------------------|
All files            |    17.43 |        0 |        0 |    17.59 |                   |
 ClientContext.js    |      100 |      100 |      100 |      100 |                   |
 GraphQLClient.js    |     1.85 |        0 |        0 |     1.89 |... 29,134,135,138 |
 index.js            |      100 |      100 |      100 |      100 |                   |
 useClientRequest.js |    14.29 |        0 |        0 |    14.29 |... 0,91,94,99,102 |
 useQuery.js         |    27.78 |        0 |        0 |    27.78 |... 27,28,29,33,35 |
---------------------|----------|----------|----------|----------|-------------------|```

SSR Support

  • graphql-hooks-ssr module
  • Should support nested queries
  • Should handle ssr errors
  • Should pre-populate cache to be used for rehydration on the client

Docs: Migrating from Apollo Guide

  • ApolloClient ➡️GraphQLClient
  • <Query /> ➡️ useQuery
  • <Mutation /> ➡️useMutation
  • client.query ➡️useManualQuery
  • SSR getDataFromTree ➡️getIntialState

Refetch queries with mutations subscription

Hello,

Description

One important feature of a graphql-client to me is the ability to refetch/update the data of a query after one or multiple mutations executions.

I really liked the idea of "a query subscribes to one or more mutations" here (see onMutation parameter) : https://github.com/arackaf/micro-graphql-react#building-queries

I started playing with the idea that we could leverage the useEffect wrapping the query fetching call and pass extra inputs to its second argument to automatically refetch the query again.

The extra inputs would take the form of a list of mutations results so whenever a subcribed mutation happens, the extra inputs changed and the query is fired again.

Suggested implementation

useQuery(GET_TODO, { id }, { refetch: ['addTodo', 'updateTodo', 'deleteTodo'] })

I made a working example of the idea here : https://codesandbox.io/s/m3nq0315m9

The general idea is to maintain of global registry of mutations results in the Context.
From here, useQuery could accept a refetch options taking a list of mutations names. Then it's just a matter of mapping the list of mutations names into a list of mutations results, and voilà, we have our extra inputs to give to useEffect.

The approach is naive but quite effective, we could complexify it a bit by accepting a tuple with an extra function given the mutation result, so we have control over the generated input given to useEffect :

useQuery(GET_TODO, { id }, { refetch: [['removeTodo', ({ id: removedId }) => id === removedId]] })

README Updates

Package

  • graphql-hooks

Environment

  • graphql-hooks version: v3.2.3 after lerna

Description

Publishing README.md only updates are tricky... The ~/packages/graphql-hooks/README.md is ignored the changes are copied over during prepublishOnly.

Here's how I got it working:

  1. Force a new version of graphql-hooks
    lerna version --conventional-commits --force-publish=graphql-hooks
  2. Publish to npm
    NPM_CONFIG_OTP=<code> lerna publish from-package

Proposed Changes

  1. Leave things as-is but document steps in CONTRIBUTING.md
  2. Change ~/packages/graphql-hooks/README.md to only be a link to the top-level README
  3. Move the top-level README into ~/packages/graphql-hooks, change top-level one to be more overview / informational with links to sub-packages. Example https://github.com/ReactTraining/react-router

Update Renovate Config to Update Examples

Package

  • examples/*

Description

React doesn't like it if there are two versions within a bundle and errors. This happened recently when we updated the packages react version in #170 - but failed to also update the examples/* package.json.

How to reproduce

n/a

Suggested solution (optional)

Update the renovate.json to override the default behaviour that ignores the examples directory.

I think it's coming from https://renovatebot.com/docs/presets-default/ which includes the following:

{
  "ignorePaths": [
    "**/node_modules/**",
    "**/bower_components/**",
    "**/vendor/**",
    "**/examples/**",
    "**/__tests__/**",
    "**/test/**",
    "**/tests/**"
  ]
}

useQuery only resends the query if options.variables change

Environment

  • graphql-hooks version: 3.1.0
  • react version: 16.8.3
  • Browser:

Description

The when calling useQuery(query, options) with different options for example operationName or fetchOptions it does not re-send the query.

How to reproduce

const QUERY = `
  query Operation1 {
    hello
  }

  query Operation2 {
    goodbye
  }
`

// example component that might change operationName based on prop
function MyComponent({ operationName }) {
  const { loading, error, data } = useQuery(QUERY, { options: { operationName } })
}

Suggested solution (optional)

// current
React.useEffect(() => {
    queryReq();
  }, [query, JSON.stringify(opts.variables)]);

// fix
React.useEffect(() => {
    queryReq();
  }, [query, JSON.stringify(opts)]);

Docs: Authentication Guide

  • Typical use case of setting a JWT via client.setHeader()
  • Include a login component that will call a login function which returns the token (could be graphql query)
  • Demonstration accessing the client via ClientContext
  • Calling setHeader with JWT
  • Refetching queries after login

Docs: Keep data from previous fetch

Description

Let's say useQuery is called based on the live contents of an input field (e.g. a filter/search box). By default, data gets set to undefined when the query arguments change, causing rendered content to flash in and out of existence – this doesn't look good. In order to keep the state from the previous fetch, updateData needs to be specified in the useQuery options (can be as trivial as { updateData: (data, nextData) => nextData }), but that's a bit unintuitive because it doesn't really explain what is actually happening under the hood (RESET_STATE isn't fired), and I'm not actually doing anything useful with updateData, like pagination.

if (!initialOpts.updateData) {
// if using updateData we can assume that the consumer cares about the previous data
dispatch({ type: actionTypes.RESET_STATE, initialState })

I'm not sure if this is a common enough use case to warrant any changes, but it might be worth adding to the docs that this is what setting updateData does.

Setup testing

  • basic react-testing-library + jest
  • CircleCI + badge
  • Stub out other tests with empty it('should...')
  • Coverage + badge

Integration test for SSR

Package

graphql-hooks-ssr

Description

Add an integration test for the SSR package, making use useQuery etc.

Console messages are nested

Environment

  • graphql-hooks version: 3.2.1
  • react version: 16.8.3
  • Browser: Safari & Chrome

Description

Second errors are nested within the first error on refetch.

screenshots are Safari & Chrome

screenshot 2019-03-04 at 11 16 58

screenshot 2019-03-04 at 11 18 22

How to reproduce

Something which fails, e.g. https://codesandbox.io/s/42k89kzpp7 (use expanded form to get the full console which has the error)

Suggested solution (optional)

Error should be somewhere here, but maybe just nested groups aren't possible?

console.groupCollapsed('---> Full Error Details');

useManualQuery does not use the cache

useManualQuery should be like a normal query and use the cache (if available). Currently the user would have to pass useCache=true for it to work as expected.

const [myQuery] = useManualQuery(MY_QUERY, { useCache: true })

Consider using lerna

It might be worth using lerna for this project. Given that we have this repo, graphql-hooks-ssr and graphql-hooks-memcache already. I expect that to grow in future so may be worth setting up a monorepo soon.

Make `cache` option required for SSR

Package

graphql-hooks-ssr

Environment

  • graphql-hooks-ssr version: 1.0.5

Description

When following the example found here, it is not immediately obvious that using a caching plugin is required. Some users might choose to begin with the simplest approach possible, and omit a cache provider.

How to reproduce

  • Follow the "Quick Start" example for graphql-hooks-ssr
  • Don't provide a cache options to GraphQLClient

Suggested solution (optional)

  • Update documentation to reflect that the cache option is required, or alternatively, update the code to not actually require it.

Add test coverage for graphql-hooks-ssr

Package

  • graphql-hooks
  • graphql-hooks-ssr
  • graphql-hooks-memcache

Description

There is currently no test coverage for graphql-hooks-ssr, we should add some.

Add support for Subscriptions

Description

We support Queries and Mutations but don't support the third operation type, Subscriptions. We should look at adding that.

Suggested implementation

I would guess websockets?

useClientRequest returns state for previous request

This cropped up when testing out useQuery with different variables after the initial request. It looks like useClientRequest returns data the second time it's called, regardless of the query/options that were passed in.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.