main

mattermost/focalboard

Last updated at: 29/12/2023 09:49

language.ts

TLDR

This file contains the implementation of the language store in the Redux store of the application. It provides methods to fetch and store the current language, as well as a reducer and selector to manage the language state.

Methods

fetchLanguage

This method is an async thunk that fetches the current language. It returns a promise that resolves with the fetched language.

storeLanguage

This method is an async thunk that stores the provided language. It calls the i18nStoreLanguage function from the ../i18n module to store the language. It returns a promise that resolves with the stored language.

Classes

None

// 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
}