useContext в react-select - не пробрасывается state

Есть простенький селект по смене языков, который должен присутствовать в двух частях сайта. Пробрасывать как-то иначе сложно, поскольку компоненты повторяются на каждой странице - нужен контекст.

LangContext:

const LangContext = createContext();

App.js:

  const options = [
    {
        value: 'ru',
        label: 'RU',
    },
    {
        value: 'en',
        label: 'EN',
    },
];

function App() {

    const [currentCountry, setCurrentCountry] = useState({
        getValue: getValue,
        onChange: onChange,
        options: options,
        lang: 'ru'
    });



    function getValue() {
        return currentCountry.lang ? options.find(c => c.value === currentCountry.lang) : '';
        
    }

    function onChange(newValue) {
        setCurrentCountry({...currentCountry, lang: newValue.value});
    }


    return (
        <LangContext.Provider value={currentCountry}>
            <Router>
                <Suspense fallback={<Spinner />}>
                    <Routes>
                        <Route path='/' element={<CabinetHome />} />
                        <Route path='*' element={<Page404 />} />
                    </Routes>
                </Suspense>
            </Router>
        </LangContext.Provider>
    );
}

Component 1:

export default function CabinetHeader() {
    const context = useContext(LangContext);
    

    return (
            <Select
                        classNamePrefix='lang-list'
                        onChange={context.onChange}
                        value={context.getValue()}
                        className='lang__list'
                        options={context.options}
                    />
    );
}

Component 2:

export default function Footer() {
    const context = useContext(LangContext);

    return (
        
                    <Select
                        classNamePrefix='lang-list'
                        onChange={context.onChange}
                        value={context.getValue()}
                        className='lang__list'
                        options={context.options}
                    />
    );
}

В данный момент state при выборе языка не обновляется, соответственно язык не меняется, а также компоненты не синхронизированы. Как сделать рабочий код?


Ответы (1 шт):

Автор решения: Yuriy Sidorov

Вытащите из стейта getValue и засуньте его в value provider:

const [currentCountry, setCurrentCountry] = useState({
    onChange: onChange,
    options: options,
    lang: "ru"
  });  

<LangContext.Provider value={{...currentCountry, getValue}}>
→ Ссылка