0

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?

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.