Replies: 14 comments 3 replies
-
Although I generally understand this example: #41 (comment), I have no idea how on a socket event, a Can you please provide a full cycle example? something like fetching api/allComments > emitting a new comment > reacting to the new comment by appending it to api/allComments data. With react apollo, it's something like: const GET_COMMENTS_QUERY = gql`
query GetComments() {
comments {
id
content
}
}
`;
const COMMENTS_SUBSCRIPTION = gql`
subscription onCommentAdded() {
commentAdded() {
id
content
}
}
`;
function CommentsPage({ params }) {
const { subscribeToMore, ...result } = useQuery(GET_COMMENTS_QUERY);
return (
<CommentsPage
{...result}
subscribeToNewComments={() =>
subscribeToMore({
document: COMMENTS_SUBSCRIPTION,
variables: { repoName: params.repoName },
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
const newFeedItem = subscriptionData.data.commentAdded;
return Object.assign({}, prev, {
entry: {
comments: [newFeedItem, ...prev.entry.comments]
}
});
}
})
}
/>
);
}```
Thank you!
|
Beta Was this translation helpful? Give feedback.
-
can the swr mutation run a refetchQueries like apolo useMutation does? |
Beta Was this translation helpful? Give feedback.
-
@vasco3 if you have the query you used to get the data in useSWR you could run |
Beta Was this translation helpful? Give feedback.
-
@sergiodxa that would work. Thanks |
Beta Was this translation helpful? Give feedback.
-
Intresting! Going to play with this! |
Beta Was this translation helpful? Give feedback.
-
Now that I'm implementing, I realize that |
Beta Was this translation helpful? Give feedback.
-
You don’t need fetcher to call mutate, if you only pass the cache key that will make the useSWR calls revalidate the data |
Beta Was this translation helpful? Give feedback.
-
I know, but I need to also mutate the database. According to the docs
I'm using the fetcher to post the mutation to the serverside. Or which would be the ideal case? For example: I'm fetching a list of users (id and user name). Then I edit a user name. I use |
Beta Was this translation helpful? Give feedback.
-
This is what I usually do (simplified): function UserList() {
const { data } = useSWR("/api/users", fetcher, { suspense: true });
return data.map(user => <User key={user.id} {...user} />)
} Then, somewhere else, when I need to update a single user, let's say inside the User component, I have a function like this: async function updateUser(id, fields) {
const res = await fetch(`/api/users/${id}`, { method: "PATCH", body: JSON.stringify(fields) });
mutate("/api/users");
} And now my list of users will revalidate itself and get the updated user, so I first mutate the DB (PATCH to the API) and then trigger a revalidate to GET the updated list, most of the time the GET is fast enough to don't feel a difference, if I needed and Optimistic UI update I would do something like: async function updateUser(id, fields) {
// this does the optimistic UI to the list
mutate("/api/users", users => { /* find and update user here */ }, false);
// here we mutate the DB
const res = await fetch(`/api/users/${id}`, { method: "PATCH", body: JSON.stringify(fields) });
// here we revalidate the list to ensure we are always up-to-date with the DB
mutate("/api/users");
} |
Beta Was this translation helpful? Give feedback.
-
Ok I see. In my case I'm using So my fetcher is passed in nextjs <SWRConfig value={{ fetcher }}>
<Component {...pageProps} />)}
</SWRConfig> and my fetcher looks like this const fetcher = (query, source = 'FAUNA', ...args) => {
const graphQLClient = (src => {
switch (src) {
case 'MONDAY':
return new GraphQLClient('https://api.monday.com/v2', {
headers: { authorization: org?.settings?.mondayApiKey?.config },
});
case 'FAUNA':
default:
return new GraphQLClient('https://graphql.fauna.com/graphql', {
headers: {
authorization: `Bearer ${org?.serverSecret}`,
'X-Schema-Preview': 'partial-update-mutation',
},
});
}
})(source);
// Creates an object. Odd indexes are keys and even indexes are values.
// Needs to be flat to avoid unnecessary rerendering since swr does shallow comparison.
const variables = [...(args || [])].reduce((acc, arg, index, arr) => {
if (index % 2 === 0) acc[arg] = arr[index + 1];
return acc;
}, {});
return graphQLClient.request(print(query), variables);
}; That's why I would like to reuse the fetcher to call my external mutation calls. I'm not happy about having the auth token on runtime JS. I would rather have it on an http-only cookie, but I see no other way to make it work with Fauna's graphql (I think they are working on this case). It helps to see your approach, thanks |
Beta Was this translation helpful? Give feedback.
-
@vasco3 we use a service worker to inject auth headers into specific requests. You could try use that here? |
Beta Was this translation helpful? Give feedback.
-
@HofmannZ what is the advantage of using a service worker for this? I'll take a look |
Beta Was this translation helpful? Give feedback.
-
Proponents of GraphQL + SWR combination 🙏 How do you approach query revalidation with the way it's shown in docs? useSWR(
`{
Movie(title: "Inception") {
releaseDate
actors {
name
}
}
}`,
fetcher
) The best thing I can imagine is to export all queries and revalidate them by names: useSWR(
MOVIES_QUERY,
fetcher
) Apollo-Client (being as hard to use as it is) has at least some rudimental convienience. I don't see any benefit of SWR over Apollo-Client, except for the lower entry barrier for the simplest of cases. Update: URQL a better choice than Apollo-Client for 2021 i.m.o. Apollo-Client development is stagnating while URQL has made a great progres in terms of docs and stability. I'ved used both document-based and graph-based caches successfully. TLDR: choose SWR for REST APIs and Urql for GraphQL APIs – you won't regret. |
Beta Was this translation helpful? Give feedback.
-
It does not seem like SWR supports subscriptions: Comparison of React Query, SWR, Apollo Client, Relay Subscriptions seem like an edge use case, according to Apollo's subscriptions doc: "In the majority of cases, your client should not use subscriptions to stay up to date with your backend. Instead, you should poll intermittently with queries, or re-execute queries on demand when a user performs a relevant action." You can apparently use the apollographql/graphql-subscriptions small npm module with any GraphQL client and server (not only Apollo). Hope this helps someone. |
Beta Was this translation helpful? Give feedback.
-
I'm maintaining a Next js application that relies on Apollo to fetch data, infinite scroll and do updates in realtime (chat like updates). SWR seems to work better with Next js with no boilerplate code. I'm considering migrating to SWR but have no idea how to replicate some react-apollo features like components subscribing to updates via Graphql. Are there any examples of SWR working with graphql Subscriptions as in react-apollo https://www.apollographql.com/docs/react/data/subscriptions/?
Beta Was this translation helpful? Give feedback.
All reactions