@ismeth/urql-sse-exchange
v1.0.3
Published
This library is based on now deprecated `@grafbase/urql-exchange` and is a drop-in replacement for it.
Downloads
30
Readme
This library is based on now deprecated @grafbase/urql-exchange
and is a drop-in replacement for it.
@ismeth/urql-sse-exchange
URQL-exchange for handling Server Sent Events (SSE)
Getting Started
Follow these steps in a new or existing React application
- Install the dependencies
npm install urql graphql @ismeth/urql-sse-exchange
- Create URQL client
// client.ts
import { cacheExchange, createClient, fetchExchange } from 'urql'
import { sseExchange } from '@ismeth/url-sse-exchange'
// Token generated by your auth provider: https://grafbase.com/docs/reference/directives#auth
const token = '....'
export const client = createClient({
url: process.env.GRAFBASE_API_URL,
fetchOptions: {
headers: {
authorization: `Bearer ${token}`
}
},
// Make sure `sseExchange` is put before `fetchExchange`
exchanges: [cacheExchange, sseExchange, fetchExchange]
})
- Connect URQL client to React
// index.ts
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { Provider } from 'urql'
import { client } from './client'
ReactDOM.createRoot(document.getElementById('root')).render(
<Provider value={client}>
<App />
</Provider>
)
- Subscribe to data changes
// App.tsx
import { useQuery, gql } from 'urql'
const query = gql`
query @live {
todoListCollection(first: 5) {
edges {
node {
id
title
}
}
}
}
`
function App() {
const [{ data, fetching, error }] = useQuery({ query })
if (fetching) return <p>Loading...</p>
if (error) return <p>Error : {error.message}</p>
return (
<>
{data?.todoListCollection?.edges?.map(
({ node: { id, title } }: { node: { id: string; title: string } }) => (
<div key={id}>
<div>{title}</div>
</div>
)
)}
</>
)
}
export default App