Skip to content

Commit

Permalink
#32 useEffect dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
RossellaFer committed Apr 26, 2024
1 parent c89bff1 commit 7346b24
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
8 changes: 4 additions & 4 deletions src/components/LocaleToggle/LocaleToggle.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FC, useEffect, useState } from 'react'
import { FC, useEffect, useState, useCallback } from 'react'
import ToggleButton from '@mui/material/ToggleButton'
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'
import { useTranslation } from 'react-i18next';
Expand All @@ -8,12 +8,12 @@ const LocaleToggle: FC = () => {
const [locale, setLocale] = useState(Locale.EN);
const { i18n } = useTranslation();

const changeLanguage = async (nextLocale: Locale) => {
const changeLanguage = useCallback(async (nextLocale: Locale) => {
await i18n.changeLanguage(nextLocale).then(() => {
setLocale(nextLocale);
localStorage.setItem('locale', nextLocale);
});
}
}, [i18n]);

useEffect(() => {
const savedLocale = localStorage.getItem('locale');
Expand All @@ -22,7 +22,7 @@ const LocaleToggle: FC = () => {
console.error(e)
})
}
}, []);
}, [changeLanguage]);

const handleChange = (_: React.MouseEvent<HTMLElement>, nextLocale: Locale) => {
changeLanguage(nextLocale).catch((e: Error) => {
Expand Down
16 changes: 10 additions & 6 deletions src/components/LocaleToggle/__test__/LocaleToggle.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,22 @@ import { describe, expect, it } from 'vitest'
import { render } from '@/tests/customRender'
import LocaleToggle from '../LocaleToggle';
import userEvent from '@testing-library/user-event'
import { screen } from '@testing-library/react'

describe('LocaleToggle', () => {
it('renders correctly', () => {
const { getByText } = render(<LocaleToggle />);
expect(getByText('English')).toBeInTheDocument();
expect(getByText('日本語')).toBeInTheDocument();
it('renders correctly', async () => {
render(<LocaleToggle />)

const english = await screen.findByText('English');
const japanese = await screen.findByText('日本語');
expect(english).toBeInTheDocument();
expect(japanese).toBeInTheDocument();
});
})

it('changes locale when toggling', async () => {
const { getByText } = render(<LocaleToggle />);
const japaneseButton = getByText('日本語');
render(<LocaleToggle />);
const japaneseButton = screen.getByText('日本語');

const user = userEvent.setup()
await user.click(japaneseButton)
Expand Down

0 comments on commit 7346b24

Please sign in to comment.