Skip to content

Commit

Permalink
Change: Rework LocaleObserver into a function component
Browse files Browse the repository at this point in the history
Make LocaleObserver easier to understand by using a function component.
  • Loading branch information
bjoernricks committed Apr 4, 2024
1 parent 4b91a1a commit 741d187
Showing 1 changed file with 23 additions and 52 deletions.
75 changes: 23 additions & 52 deletions src/web/components/observer/localeobserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,65 +15,36 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';

import {connect} from 'react-redux';
import React, {useEffect, useState} from 'react';

import {onLanguageChange} from 'gmp/locale/lang';

import {isDefined} from 'gmp/utils/identity';

import PropTypes from 'web/utils/proptypes';

import {setLocale} from 'web/store/usersettings/actions';

class LocaleObserver extends React.Component {
constructor(...args) {
super(...args);

this.state = {};

this.handleLanguageChange = this.handleLanguageChange.bind(this);
}

componentDidMount() {
this.unsubscribeFromLanguageChange = onLanguageChange(
this.handleLanguageChange,
);
}

componentWillUnmount() {
if (isDefined(this.unsubscribeFromLanguageChange)) {
this.unsubscribeFromLanguageChange();
}
}

handleLanguageChange(locale) {
this.props.setLocale(locale);

this.setState({locale});
}

render() {
const {children} = this.props;
const {locale} = this.state;
import useLocale from 'web/hooks/useLocale';

if (!isDefined(locale)) {
// don't render if no locale has been detected yet
return null;
}

return <React.Fragment key={locale}>{children}</React.Fragment>;
/**
* A component that observes the locale, puts it into the redux store and
* re-renders its children whenever the locale changed
*/
const LocaleObserver = ({children}) => {
const [locale, setLocaleState] = useState();
const [, setLocale] = useLocale();

useEffect(() => {
const unsubscribeFromLanguageChange = onLanguageChange(newLocale => {
setLocaleState(newLocale);
setLocale(newLocale);
});
return unsubscribeFromLanguageChange;
}, [setLocale, setLocaleState]);

if (!isDefined(locale)) {
// don't render if no locale has been detected yet
return null;
}
}

LocaleObserver.propTypes = {
setLocale: PropTypes.func.isRequired,
return <React.Fragment key={locale}>{children}</React.Fragment>;
};

export default connect(
undefined,
{
setLocale,
},
)(LocaleObserver);
export default LocaleObserver;

0 comments on commit 741d187

Please sign in to comment.