In my production environment, I’m not getting real-time updates on the client side. The backend and GraphQL API are both working fine. (Since my previous issue isn’t resolved yet, I don’t want to be advised on to check if subscriptions are working fine in my sandbox playground)
import { configureStore } from "@reduxjs/toolkit"
import authReducer, { reset } from "../features/auth/authSlice"
import crowdReducer, { resetCrowdState } from "../features/user/crowdSlice"
import onboardReducer, { resetBillingState } from "../features/auth/billingSlice"
import { ApolloClient, InMemoryCache, ApolloProvider, gql, createHttpLink, split } from "@apollo/client"
import { GraphQLWsLink } from "@apollo/client/link/subscriptions"
import { setContext } from "@apollo/client/link/context"
import { Provider } from "react-redux"
import { getMainDefinition } from "@apollo/client/utilities"
import { createClient } from "graphql-ws"
import cloud_linkReducer, { resetCloudState } from "../features/user/cloudSlice"
const isDevelopment = process.env.VITE_NODE_ENV == "development"
const serverUrl = isDevelopment ? `${process.env.VITE_LOCALHOST}:${process.env.VITE_PORT}` : process.env.CLIENT_URL
const wsUrl = isDevelopment ? `ws://localhost:${process.env.VITE_PORT}/api/v1/graphql` : `wss://www.abc.com/api/v1/graphql`
export const store = configureStore({
reducer: {
auth: authReducer,
crowd: crowdReducer,
onboard: onboardReducer,
cloud: cloud_linkReducer,
},
devTools: isDevelopment,
})
export const resetAllState = () => (dispatch) => {
dispatch(reset())
dispatch(resetBillingState())
dispatch(resetCrowdState())
dispatch(resetCloudState())
}
const httpLink = new createHttpLink({
uri: `${serverUrl}/api/v1/graphql`,
})
const authLink = setContext((_, { headers }) => {
const client = localStorage.getItem("client")
let token
try {
token = client ? JSON.parse(client).token : null
} catch (error) {
console.error("Failed to parse client token from local storage", error)
}
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
},
}
})
// Create a WebSocket client
const wsClient = createClient({
url: wsUrl,
connectionParams: () => ({
token: JSON.parse(localStorage.getItem("client"))?.token,
}),
})
// Create a WebSocket link and use split for proper link selection
const wsLink = new GraphQLWsLink(wsClient)
const link = split(
({ query }) => {
const definition = getMainDefinition(query)
return definition.kind === "OperationDefinition" && definition.operation === "subscription"
},
wsLink,
authLink.concat(httpLink)
)
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
})
// Wrap your app with ApolloProvider and Redux Provider
export const AppProviders = ({ children }) => {
return (
<ApolloProvider client={client}>
<Provider store={store}>{children}</Provider>
</ApolloProvider>
)
}