Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement miles/kilometer selector #252

Merged
merged 11 commits into from
Oct 6, 2019
Prev Previous commit
Next Next commit
feat: create DistanceUnit Store
  • Loading branch information
matepapp committed Oct 5, 2019
commit e9f80e07d91aba0692f061f122bccd064386050c
54 changes: 54 additions & 0 deletions App/stores/distanceUnit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { AsyncStorage } from 'react-native';
import React, { useState, useEffect, createContext, FC, useContext } from 'react';
amaury1093 marked this conversation as resolved.
Show resolved Hide resolved

import { i18n } from '../localization';
import { noop } from '../util/noop';

export type DistanceUnit = 'km' | 'mile';
type DistanceUnitFormat = 'short' | 'long';

const STORAGE_KEY = 'DISTANCE_UNIT';

type ContextType = {
distanceUnit: DistanceUnit;
setDistanceUnit: (distanceUnit: DistanceUnit) => void;
localizedDistanceUnit: (format: DistanceUnitFormat) => string;
};

const Context = createContext<ContextType>({
distanceUnit: 'km',
localizedDistanceUnit: (format: DistanceUnitFormat) => '',
setDistanceUnit: (unit: DistanceUnit) => {}
});

export const DistanceUnitProvider: FC = ({ children }) => {
amaury1093 marked this conversation as resolved.
Show resolved Hide resolved
const [distanceUnit, setDistanceUnit] = useState<DistanceUnit>('km');
amaury1093 marked this conversation as resolved.
Show resolved Hide resolved

const getDistanceUnit = async (): Promise<void> => {
const unit = await AsyncStorage.getItem(STORAGE_KEY);
if ((unit && unit === 'km') || (unit && unit === 'mile')) {
matepapp marked this conversation as resolved.
Show resolved Hide resolved
setDistanceUnit(unit);
}
};

const localizedDistanceUnit = (format: 'short' | 'long'): string =>
distanceUnit === 'km'
? i18n.t(`distance_unit_${format}_km`)
: i18n.t(`distance_unit_${format}_mi`);

useEffect(() => {
getDistanceUnit();
}, []);

useEffect(() => {
AsyncStorage.setItem(STORAGE_KEY, distanceUnit);
}, [distanceUnit]);

return (
<Context.Provider value={{ distanceUnit, setDistanceUnit, localizedDistanceUnit }}>
{children}
</Context.Provider>
);
};

export const useDistanceUnit = () => useContext(Context);
1 change: 1 addition & 0 deletions App/stores/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ export * from './api';
export * from './error';
export * from './frequency';
export * from './location';
export * from './distanceUnit';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alphabetical