Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
an naive version of react-apollo Query
import { createContext } from '@xialvjun/create-react-context';
import { create_client } from '@xialvjun/tiny-graphql-client';
import React, { Component } from 'react';
const tiny_client = create_client(async (body, extra_headers) => {
const res = await fetch('http://127.0.0.1:3000/graphql', {
method: 'post',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.__TOKEN__}`,
...extra_headers,
},
});
const obj = await res.json();
if (obj.error) {
throw obj.error;
}
return obj.data;
});
const GraphqlState = createContext({
state: { },
key(query, variables) {
return query + JSON.stringify(variables);
},
get(query, variables) {
const key = this.key(query, variables);
return this.state[key] || { loading: true };
},
async run(query, variables, network_only=false) {
const key = this.key(query, variables);
let value = this.state[key] || {};
let { data, loading, error } = value;
if (!!loading) {
return loading;
}
if (network_only || !data) {
loading = tiny_client.run(query, variables);
this.setState({ [key]: { ...value, loading } });
try {
data = await loading;
this.setState({ [key]: { data } });
} catch (error) {
this.setState({ [key]: { data, error } });
}
}
return data;
},
});
export class Client extends Component {
runed = {}
render() {
const { query, variables, network_only, children } = this.props;
const ctx = GraphqlState.getContext();
if (!network_only) {
ctx.run(query, variables, network_only);
} else {
const key = ctx.key(query, variables);
if (network_only && !this.runed[key]) {
this.runed[key] = true;
ctx.run(query, variables, network_only);
}
}
return <GraphqlState>
{ctx => children(ctx.get(query, variables))}
</GraphqlState>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment