main

mattermost/focalboard

Last updated at: 28/12/2023 01:37

language.ts

TLDR

This file (language.ts) contains code related to handling the language state in the Redux store of the web application. It includes async thunks for fetching and storing language, a language reducer, and a selector function to get the current language from the state.

Methods

fetchLanguage

This method is an async thunk action creator that fetches the current language. It returns the getCurrentLanguage function.

storeLanguage

This method is an async thunk action creator that stores the selected language in the application. It takes a lang parameter and stores it using the i18nStoreLanguage function. It returns the lang parameter.

Classes

N/A

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.

import {createSlice, createAsyncThunk, PayloadAction} from '@reduxjs/toolkit'

import {getCurrentLanguage, storeLanguage as i18nStoreLanguage} from '../i18n'

import {RootState} from './index'

export const fetchLanguage = createAsyncThunk(
    'language/fetch',
    async () => getCurrentLanguage(),
)

export const storeLanguage = createAsyncThunk(
    'language/store',
    (lang: string) => {
        i18nStoreLanguage(lang)
        return lang
    },
)

const languageSlice = createSlice({
    name: 'language',
    initialState: {value: 'en'} as {value: string},
    reducers: {
        setLanguage: (state, action: PayloadAction<string>) => {
            state.value = action.payload
        },
    },
    extraReducers: (builder) => {
        builder.addCase(fetchLanguage.fulfilled, (state, action) => {
            state.value = action.payload
        })
        builder.addCase(storeLanguage.fulfilled, (state, action) => {
            state.value = action.payload
        })
    },
})

export const {reducer} = languageSlice

export function getLanguage(state: RootState): string {
    return state.language.value
}