George
George

Reputation: 1050

React apollo default query variable from redux store

I am trying to make a multilingual single page application using react-apollo. The сurrent locale is stored in redux store. The problem is that I have to connect every component to redux just to pass locale variable to the query. Such repetition of code looks redundant. I cannot hardcode locale to the query because it can be different for different users. I need to pass default value dynamically. Any ideas?

Upvotes: 0

Views: 266

Answers (1)

Mjuice
Mjuice

Reputation: 1288

You could add the locale as a header to every request you send to your server using the apollo client's middleware. Store the locale in localStorage if you are using a browser, or asyncStorage if you are using react native.

import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { GRAPHQL_API_DEV } from './api';
import { checkForLocale } from '../../utils/locale';

const networkInterface = createNetworkInterface({
  uri: GRAPHQL_API_DEV
});

networkInterface.use([{
  applyMiddleware(req, next) {
    // Create the header object if needed.
    if (!req.options.headers) {
      req.options.headers = {};
    }

    // get the locale token from Async storage
    // and assign it to the request object
    checkForLocale()
    .then(LOCALE => {
      req.options.headers.custom-header = LOCALE;
      next();
    })
    .catch(error => {
      req.options.headers.custom-header = null;
      next();
    })
  }
}]);

const client = new ApolloClient({
  networkInterface,
  dataIdFromObject: o => o.id
});

export default client;

Upvotes: 1

Related Questions