Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@doodle/i18n / src / state / saga / index.js
Size: Mime:
import { takeLatest, call, put, all, select } from 'redux-saga/effects';
import { addLocaleData } from 'react-intl';

import { ActionTypes, fetchMessagesSuccess, fetchMessagesError } from '../actions';

import { flatten } from '../../onesky/transform';
import cookie from '../../cookie';

import { importIntl, importLocaleData, importMessages } from '../../import';
import getCookieDomain from './getCookieDomain';

function* onChangeLocale(options, action) {
  const { locale } = action.payload;
  const cookieDomain = getCookieDomain();
  const reduxState = yield select(state => state[options.domain || 'i18n']);
  const { messages } = reduxState;

  cookie.set('locale', locale, undefined, cookieDomain);
  if (document.documentElement) {
    document.documentElement.lang = locale;
  }

  if (!messages[locale]) {
    try {
      const { messagesData, reactIntlLocaleData } = yield all({
        intl: call(importIntl),
        reactIntlLocaleData: call(importLocaleData, locale),
        messagesData: call(importMessages, locale),
      });
      if (reactIntlLocaleData) {
        addLocaleData(reactIntlLocaleData);
      }
      yield put(fetchMessagesSuccess(locale, flatten(messagesData)));
    } catch (error) {
      yield put(fetchMessagesError(error));
    }
  }
}

function* onFetchMessages(options, action) {
  try {
    const { locale } = action.payload;
    const messages = yield call(importMessages, locale);
    yield put(fetchMessagesSuccess(locale, messages));
  } catch (error) {
    yield put(fetchMessagesError(error));
  }
}

function* watchChangeLocale(options) {
  yield takeLatest(ActionTypes.CHANGE_LOCALE, onChangeLocale, options);
}

function* watchFetchMessages(options) {
  yield takeLatest(ActionTypes.FETCH_MESSAGES, onFetchMessages, options);
}

export default function* loadI18NSaga(options = {}) {
  yield all([call(watchChangeLocale, options), call(watchFetchMessages, options)]);
}