I am trying to subscribe to a graphql-yoga subscription using apollo-client useSubscription hook
import React from 'react';
import {useSubscription,gql} from '#apollo/client';
const SUB_NEW_MSG = gql`
subscription SUB_NEW_MSG($chatRoom:ID!)
{
newMessage(chatRoom:$chatRoom)
}`;
function NewMsg(){
const { loading,error,data } = useSubscription(SUB_NEW_MSG,{
variables:{
chatRoom: "608851227be4796a8463607a",
},
});
if(loading) return <p>loading...</p>;
if(error) return <p>{error}</p>;
console.log(data);
return <h4>New Message:{data.newMessage}</h4>;
}
Network Status
But gives an error-
Error: Objects are not valid as a React child (found: Error: Variable "$chatRoom" of required type "ID!" was not provided.). If you meant to render a collection of children, use an array instead.
The schema at the backend is
type Subscription{
newMessage(chatRoom: ID!): String!
}
resolver is
const { pubsub } = require("../helper");
const { withFilter } = require("graphql-yoga");
module.exports = {
Subscription: {
newMessage: {
subscribe: withFilter(
() => pubsub.asyncIterator("newMessage"),
(payload, variables) => {
console.log(payload.query, variables, "HALO");
return payload.chatRoom === variables.chatRoom;
}
),
},
},
};
But when I pass the query like below,with no variables to useSubscription hook.Then it works
const SUB_NEW_MSG = gql`
subscription SUB_NEW_MSG
{
newMessage(chatRoom:"608851227be4796a8463607a")
}`;
What should I do?Are there any workarounds?
Change your query to this, and test it.
const SUB_NEW_MSG = gql`
subscription SUB_NEW_MSG($chatRoom: String!) {
newMessage(chatRoom: $chatRoom)
}
`;
Related
I want to add variables to my swr which fetch using graphql request. this is my code
import { request } from "graphql-request";
import useSWR from "swr";
const fetcher = (query, variables) => request(`https://graphql-pokemon.now.sh`, query, variables);
export default function Example() {
const variables = { code: 14 };
const { data, error } = useSWR(
`query GET_DATA($code: String!) {
getRegionsByCode(code: $code) {
code
name
}
}`,
fetcher
);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
but I dont know how to add variables into swr fetcher as I know useSWR(String, fetcher) string is for query, and fetcher for fetch function, where I can put the variables?
You can use Multiple Arguments, you can use an array as the key parameter for the useSWR react hook.
import React from "react";
import { request } from "graphql-request";
import useSWR from "swr";
const fetcher = (query, variables) => {
console.log(query, variables);
return request(`https://graphql-pokemon.now.sh`, query, variables);
};
export default function Example() {
const variables = { code: 14 };
const { data, error } = useSWR(
[
`query GET_DATA($code: String!) {
getRegionsByCode(code: $code) {
code
name
}
}`,
variables,
],
fetcher
);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
The function fetcher still accepts the same 2 arguments: query and variables.
SWR author here!
Agreed that this is a critical feature to have, that's why since v1.1.0, SWR keys will be serialized automatically and stably. So you can safely do this:
useSWR(['query ...', variables], fetcher)
While variables can be a JavaScript object (can be nested, or an array, too), and it will not cause any unnecessary re-renders. Also, the serialization process is stable so the following keys are identical, no extra requests:
// Totally OK to do so, same resource!
useSWR(['query ...', { name: 'foo', id: 'bar' }], fetcher)
useSWR(['query ...', { id: 'bar', name: 'foo' }], fetcher)
You can directly pass an object as the key too, it will get passed to the fetcher:
useSWR(
{
query: 'query ...',
variables: { name: 'foo', id: 'bar' }
},
fetcher
)
You can try it out by installing the latest version of SWR, let me know if there's any issue :)
The solution from slideshowp2 did not help me since it resulted in an infinite loop.
Don't pass an object to the useSWR function since they change on every re-render. Pass the variables directly:
const fetcher = (query, variables) => {
console.log(query, variables);
return request(`https://graphql-pokemon.now.sh`, query, variables);
};
export default function Example() {
const { data, error } = useSWR(
[
`query GET_DATA($code: String!) {
getRegionsByCode(code: $code) {
code
name
}
}`,
14,
],
(query, coder => fetcher(query, { code })
);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
I'm trying to use react-admin with AWS Amplify library and AWS AppSync SDK.
I can't wrap my head around how to use use ra-data-graphql/ra-data-graphql-simple with AWS AppSync API for querying/mutating data. Trying to do a very basic test with master/examples/demo from https://github.com/marmelab/react-admin/.
Any guidance will be appreciated.
Currently I'm trying to use dataProvider similar to below:
src/dataProvider/appsync.js:
import gql from 'graphql-tag';
import AWSAppSyncClient, { AUTH_TYPE } from 'aws-appsync';
import buildGraphQLProvider, { buildQuery } from 'ra-data-graphql-simple';
import { __schema as schema } from './schema';
const client = new AWSAppSyncClient({
url: "https://xxxx.appsync-api.us-east-1.amazonaws.com/graphql",
region: "us-east-1,
auth: {
type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
}
const myBuildQuery = introspection => (fetchType, resource, params) => {
const builtQuery = buildQuery(introspection)(fetchType, resource, params);
if (resource === 'listings' && fetchType === 'GET_LIST') {
return {
...builtQuery,
query: gql`
query getListings {
data: getListings {
items {
listingId
}
}
}`,
};
}
return builtQuery;
}
export default buildGraphQLProvider({ client: client, introspection: { schema }, buildQuery: myBuildQuery })
src/dataProvider/index.js:
export default type => {
switch (type) {
case 'graphql':
return import('./graphql').then(factory => factory.default());
case 'appsync':
return import('./appsync');
default:
return import('./rest').then(provider => provider.default);
}
};
src/App.js:
...
import dataProviderFactory from './dataProvider';
...
class App extends Component {
state = { dataProvider: null };
async componentDidMount() {
const dataProvider = await dataProviderFactory(
process.env.REACT_APP_DATA_PROVIDER
);
this.setState({ dataProvider });
}
...
src/dashboard/Dashboard.js:
...
fetchData() {
this.fetchListings();
}
async fetchListings() {
const { dataProvider } = this.props;
const { data: reviews } = await dataProvider(GET_LIST, 'listings');
console.log(listings)
}
...
Currently no data is returned from the API and the exception is thrown on await dataProvider(GET_LIST, 'listings'); saying call: [object Model] is not a function, however I see that buildGraphQLProvider promise was resolved succesfully to a function.
Can anyone suggest what I am doing wrong and what is the right way to approach the task?
So I'm attempting to stitch multiple remote GraphCMS endpoints together on the clientside of a Next.js app, and after trying/combining about every example on the face of the internet, I've gotten it to a place that's worth asking about. My error:
TypeError: this.getClient(...).watchQuery is not a function at GraphQL.createQuery
github repo here, where you can see this initApollo.js in context:
import { ApolloClient } from 'apollo-client'
import {
makeRemoteExecutableSchema,
mergeSchemas,
introspectSchema
} from 'graphql-tools'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import fetch from 'node-fetch'
import { Observable, ApolloLink } from 'apollo-link'
import { graphql, print } from 'graphql'
import { createApolloFetch } from 'apollo-fetch'
let apolloClient = null
if (!process.browser) {
global.fetch = fetch
}
const PRIMARY_API = 'https://api.graphcms.com/simple/v1/cjfipt3m23x9i0190pgetwf8c'
const SECONDARY_API = 'https://api.graphcms.com/simple/v1/cjfipwwve7vl901427mf2vkog'
const ALL_ENDPOINTS = [PRIMARY_API, SECONDARY_API]
async function createClient (initialState) {
const AllLinks = ALL_ENDPOINTS.map(endpoint => {
return new HttpLink({
uri: endpoint,
fetch
})
})
const allSchemas = []
for (let link of AllLinks) {
try {
allSchemas.push(
makeRemoteExecutableSchema({
schema: await introspectSchema(link),
link
})
)
} catch (e) {
console.log(e)
}
}
const mergedSchema = mergeSchemas({
schemas: allSchemas
})
const mergedLink = operation => {
return new Observable(observer => {
const { query, variables, operationName } = operation
graphql(mergedSchema, print(query), {}, {}, variables, operationName)
.then(result => {
observer.next(result)
observer.complete()
})
.catch(e => observer.error(e))
})
}
return new ApolloClient({
connectToDevTools: process.browser,
ssrMode: !process.browser,
link: mergedLink,
cache: new InMemoryCache().restore(initialState || {})
})
}
export default function initApollo (initialState) {
if (!process.browser) {
return createClient(initialState)
}
if (!apolloClient) {
apolloClient = createClient(initialState)
}
console.log('\x1b[37m%s\x1b[0m', apolloClient)
return apolloClient
}
I'm getting useful data all the way up into the .then() inside the Observable, where I can log the result
This is a shot in the dark, but initApollo isn't async so it returns a promise (not an ApolloClient object) which is then being passed into client prop of the ApolloProvider. watchQuery doesn't exist as a function on the Promise type, hence the error.
I think if you make initApollo async and then await those calls or find a way to make client creation synchronous, you should be able to address this issue.
I have a functioning web socket created with Apollo's WebSocketLink interface. I managed to subscribe to an event using subscribeToMore and a message is pushed by the server (can see it in the network tab). Unfortunately updateQuery function is never triggered. I wonder whether it's the message structure that is incorrect (therefore a wrong server implementation) or is it something wrong in my client code.
For reference I added the message sent from server:
and here the graphql config for my component:
import { graphql } from "react-apollo/index";
import Insights from 'components/insights/Insights';
import gql from "graphql-tag";
import { withRouter } from "react-router-dom";
import get from 'lodash/get';
const query = gql`
query CampaignInsights($campaignId: ID) {
campaigns (id: $campaignId) {
edges {
node {
insights {
campaignPlanningInsight {
campaign
plannedTotals {
totalOptimizationRules
totalOfferGroups
totalOffers
}
liveTotals {
totalOptimizationRules
totalOfferGroups
totalOffers
}
}
}
}
}
}
}
`;
const insightsSubscription = gql`
subscription onInsightsUpdated($campaignId: ID) {
campaignPlanningInsightUpdated(id: $campaignId) {
id
plannedTotals {
totalOptimizationRules
totalOfferGroups
totalOffers
}
liveTotals {
totalOptimizationRules
totalOfferGroups
totalOffers
}
}
}
`;
const InsightsWithData = graphql(query, {
options: (props) => {
return {
variables: {
campaignId: props.match.params.campaignId
}
}
},
props: ({ data: { campaigns, subscribeToMore }, ownProps: { match }
}) => {
return {
insights: get(campaigns,
'edges[0].node.insights[0].campaignPlanningInsight', null),
subscribeToInsightsUpdate: () => {
return subscribeToMore({
document: insightsSubscription,
variables: {
campaignId: match.params.campaignId
},
updateQuery: (prev, { subscriptionData }) => {
debugger; // never gets here
if (!subscriptionData.data) {
return prev;
}
}
})
}
}
}
})(Insights);
export default withRouter(InsightsWithData);
I believe the issue might be the id of the graphql-ws websocket protocol.
That id needs to match the one sent by the frontend in the GQL_START message. Otherwise, the component won't re-render on a new message.
For more details, look into the subscription-transport-ws protocol
In one of my components within a redux-form onSubmit, I have the following:
const result = await helloSignup(values);
console.log(result);
helloSignup is mutating the database as expected but the const result is currently be logged as undefined
Why?
My HOC/mutation helloSignup:
export const HELLO_SIGNUP_MUTATION = gql`
mutation (
$email: String!
$code: String!
) {
signup(authProvider: {
emailAndCode: {
email: $email
code: $code
}
}) {
token
user {
id
}
}
}
`;
export default graphql(
HELLO_SIGNUP_MUTATION,
{
props: ({ mutate }) => ({
emailAndCodeSignup: async (variables) => {
const { data } = await mutate({ variables });
const { token } = data.signup;
},
}),
}
);
Using GraphiQL, I can see that my graphql mutation, returns the desired results:
{
"data": {
"signup": {
"token": "xxx",
"user": {
"id": "16"
}
}
}
}
If GraphiQL is getting the desired results after mutating, why isn't the result being console logged above?
React-Apollo provides a HOC for client side queries and mutations called withApollo.
This signature is something like this:
withApollo(MyForm)
https://www.apollographql.com/docs/react/basics/setup.html#withApollo
which adds a prop of 'client' to the MyForm component. On form submission, you'd want to access this prop, and call the mutation from there. So in your form submit handler youd end up with something like this:
https://www.apollographql.com/docs/react/basics/mutations.html#basics
onSubmit() {
const { client } = this.props
const options = {} // your mutation options
// mutations ands queries return promises,
// so you must wait for their completion before accessing data
client.mutate(
HELLO_SIGNUP_MUTATION,
options
).then(({ data }) => (
console.log('got data', data);
)
}
}
Where data should be whats coming back from the API