question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Use fetch api when supported

See original GitHub issue

I’m using i18next in a service worker setup right now with this xhr backend, however, there was one obstacle to get it working: XMLHttpRequest is not defined in the service worker context. I did manage to get the backend working in the following manner however:

import i18next from 'i18next';
import i18nextXHR from 'i18next-xhr-backend'; // eslint-disable-line import/no-unresolved,import/no-extraneous-dependencies

let t = null;

self.addEventListener('activate', (event) => {
  event.waitUntil(new Promise((resolve, reject) => {
    i18next
      .use(i18nextXHR)
      .init({
        fallbackLng: ['ja', 'en', 'zh'],
        preload: ['ja', 'en', 'zh'],
        ns: 'translation',
        defaultNS: 'translation',
        keySeparator: false, // Allow usage of dots in keys
        nsSeparator: false,
        backend: {
          loadPath: '/locales/{{lng}}/{{ns}}.json',
          ajax(url, options, cb) {
            fetch(url, options)
              .then((res) => {
                if (res.ok) {
                  return res.text()
                    .then((json) => {
                      cb(json, res);
                    });
                }

                return new Error('Error loading translation json');
              });
          },
        },
      }, (err, _t) => {
        if (err) {
          reject(err);
          return;
        }

        t = _t;
        resolve();
      });
  }));
});

By using the ajax option and using the fetch API, this backend works like charm… however, maybe it’s a good idea to use the fetch API here wherever it’s supported by default? It’s a more modern API supported by modern browsers, and would make using i18next in service worker contexts, or other modern context much more easy

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

4reactions
perrin4869commented, Jan 23, 2017

Just published the module here

2reactions
perrin4869commented, Jan 22, 2017

Actually, what do you think of this as the fetch-backend:

import XHRBackend from 'i18next-xhr-backend';

class FetchBackend extends XHRBackend {
  constructor(services, options = {}) {
    options.ajax = options.ajax || ((url, options, cb) => {
      fetch(url, options)
        .then((res) => {
          if (res.ok) {
            return res.text()
              .then((json) => {
                cb(json, res);
              });
          }

          return new Error('Error loading translation json');
        });
    });

    super(services, options);
  }
}

Just tested it and seems to work in my case. I’ll publish it as an npm module tomorrow

Read more comments on GitHub >

github_iconTop Results From Across the Web

Fetch API - MDN Web Docs
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used ...
Read more >
Fetch | Can I use... Support tables for HTML5, CSS3, etc
"Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile web browsers.
Read more >
JavaScript Fetch API Explained By Examples
The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a...
Read more >
The Fetch API is finally coming to Node.js - LogRocket Blog
It's been a long time coming, but the Fetch API is now available in Node.js core. Learn why it took so long and...
Read more >
Fetch API in Node.js - Atatus
In all popular browsers, the Fetch API has native support. The node-fetch package is used by JavaScript developers to create server-side code.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found