Преглед на файлове

extract AppContextProvider

mightyplow преди 5 години
родител
ревизия
5a227fb72c
променени са 3 файла, в които са добавени 35 реда и са изтрити 23 реда
  1. 3 22
      src/layout/App.tsx
  2. 1 1
      src/layout/AppContext.ts
  3. 31 0
      src/layout/AppContextProvider.tsx

+ 3 - 22
src/layout/App.tsx

@@ -1,37 +1,18 @@
-import React, { ReactElement, useEffect, useState } from 'react';
+import React, { ReactElement } from 'react';
 import {
   BrowserRouter as Router,
   Route,
   Switch
 } from 'react-router-dom';
 import { CaloriesList } from '../components/caloriesList/CaloriesList';
-import { AppContext } from './AppContext';
+import { AppContextProvider } from './AppContextProvider';
 import { PageFooter } from './pageFooter/PageFooter';
 import { PageHeader } from './pageHeader/PageHeader';
-
 import './app.css';
 
-const AppContextProvider = AppContext.Provider;
-const storedCalories = JSON.parse(localStorage.getItem('calorieItems') || '[]');
-
 function App (): ReactElement {
-  const [calorieItems, setCalorieItems] = useState<CalorieItems>(storedCalories);
-  const [selectedDate, setSelectedDate] = useState<number>(Date.now());
-  const [selectedItem, setSelectedItem] = useState<CalorieValue>();
-
-  useEffect(() => {
-    localStorage.setItem('calorieItems', JSON.stringify(calorieItems));
-  });
-
   return (
-    <AppContextProvider value={{
-      calorieItems,
-      selectedDate,
-      selectedItem,
-      setCalorieItems,
-      setSelectedDate,
-      setSelectedItem
-    }}>
+    <AppContextProvider >
       <PageHeader />
 
       <main id="pageContent">

+ 1 - 1
src/layout/AppContext.ts

@@ -16,7 +16,7 @@ const AppContext = createContext<AppContextType>({
   selectedItem: undefined,
   setCalorieItems: () => [],
   setSelectedDate: () => getDateString(new Date()),
-  setSelectedItem: () => {}
+  setSelectedItem: () => undefined
 });
 
 export {

+ 31 - 0
src/layout/AppContextProvider.tsx

@@ -0,0 +1,31 @@
+import React, { useEffect, useState } from 'react';
+import { AppContext } from './AppContext';
+
+const ContextProvider = AppContext.Provider;
+
+const storedCalories = JSON.parse(localStorage.getItem('calorieItems') || '[]');
+
+function AppContextProvider (props: object) {
+  const [calorieItems, setCalorieItems] = useState<CalorieItems>(storedCalories);
+  const [selectedDate, setSelectedDate] = useState<number>(Date.now());
+  const [selectedItem, setSelectedItem] = useState<CalorieValue>();
+
+  useEffect(() => {
+    localStorage.setItem('calorieItems', JSON.stringify(calorieItems));
+  });
+
+  return (
+    <ContextProvider value={{
+      calorieItems,
+      selectedDate,
+      selectedItem,
+      setCalorieItems,
+      setSelectedDate,
+      setSelectedItem
+    }} {...props} />
+  );
+}
+
+export {
+  AppContextProvider
+};