File tree Expand file tree Collapse file tree 2 files changed +32
-23
lines changed Expand file tree Collapse file tree 2 files changed +32
-23
lines changed Original file line number Diff line number Diff line change 1
1
import { useMemo } from "react" ;
2
- import { GraphQLSchema } from "graphql" ;
2
+ import { GraphQLSchema , DocumentNode } from "graphql" ;
3
3
import graphql from "reactive-graphql" ;
4
- import gql from "graphql-tag" ;
5
4
6
5
import useObservable from "./useObservable" ;
7
6
7
+ type ReactiveGraphQLResponse = {
8
+ data : any ;
9
+ } ;
10
+
8
11
export default function getReactiveGraphqlReact ( schema : GraphQLSchema ) {
9
- return function reactiveGraphqlReact ( query : string , context ?: Object ) {
10
- const observable = useMemo (
11
- ( ) =>
12
- graphql (
13
- gql `
14
- ${ query }
15
- ` ,
16
- schema ,
17
- context || { }
18
- ) ,
19
- [ query , JSON . stringify ( context ) ]
20
- ) ;
12
+ if ( ! ( schema instanceof GraphQLSchema ) ) {
13
+ throw new Error ( "schema needs to be a GraphQLSchema" ) ;
14
+ }
21
15
22
- return useObservable ( observable , null ) ;
16
+ return function useReactiveGraphqlReact (
17
+ query : DocumentNode ,
18
+ context ?: Object
19
+ ) {
20
+ const observable = useMemo ( ( ) => graphql ( query , schema , context || { } ) , [
21
+ query ,
22
+ JSON . stringify ( context )
23
+ ] ) ;
24
+
25
+ const [ data , errors ] = useObservable < ReactiveGraphQLResponse , any [ ] > (
26
+ observable ,
27
+ null
28
+ ) ;
29
+ return [ data === null ? data : data . data , errors ] ;
23
30
} ;
24
31
}
Original file line number Diff line number Diff line change 1
1
import { useState , useEffect } from "react" ;
2
+ import { Observable } from "rxjs" ;
2
3
3
- export default function useObservable ( observable$ , initialValue ) {
4
+ export default function useObservable < T , E > (
5
+ observable$ : Observable < T > ,
6
+ initialValue : T | null = null
7
+ ) : [ T , E ] {
4
8
const [ value , update ] = useState ( initialValue ) ;
5
9
const [ error , updateError ] = useState ( null ) ;
6
10
7
- useEffect (
8
- ( ) => {
9
- const s = observable$ . subscribe ( update , updateError ) ;
10
- return ( ) => s . unsubscribe ( ) ;
11
- } ,
12
- [ observable$ ]
13
- ) ;
11
+ useEffect ( ( ) => {
12
+ const s = observable$ . subscribe ( update , updateError ) ;
13
+
14
+ return ( ) => s . unsubscribe ( ) ;
15
+ } , [ observable$ ] ) ;
14
16
15
17
return [ value , error ] ;
16
18
}
You can’t perform that action at this time.
0 commit comments