Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { createContext, useReducer, useContext } from 'react';
- import PropTypes from 'prop-types';
- import en_US from 'antd/lib/locale-provider/en_US';
- import zh_TW from 'antd/lib/locale-provider/zh_TW';
- import zh_CN from 'antd/lib/locale-provider/zh_CN';
- import { userInitialState, userActions } from './user';
- const locales = {
- en_US,
- zh_TW,
- zh_CN
- }
- const getAntdLocale = (lang) => {
- var locale = locales.en_US;
- if(lang==='zh_Hant') locale = locales.zh_TW;
- if(lang==='zh_Hans') locale = locales.zh_CN;
- return locale;
- }
- const initialState = {
- lang: localStorage.getItem('lang') || 'en',
- antdLocale: getAntdLocale(localStorage.getItem('lang')||'en_US'),
- ...userInitialState
- };
- const StoreContext = createContext(initialState);
- const Actions = {
- changeLang: (state, lang) => {
- localStorage.setItem('lang', lang);
- return {lang, antdLocale: getAntdLocale(lang)};
- },
- ...userActions
- };
- const reducer = (state, action) => {
- const act = Actions[action.type];
- const update = act(state, action.payload);
- return { ...state, ...update };
- };
- export const StoreProvider = ({ children }) => {
- const [state, dispatch] = useReducer(reducer, initialState);
- return <StoreContext.Provider value={{ state, dispatch }}>{children}</StoreContext.Provider>;
- };
- StoreProvider.propTypes = {
- children: PropTypes.node
- };
- export const useStore = store => {
- const { state, dispatch } = useContext(StoreContext);
- return { state, dispatch };
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement