From 7388f3e05dedc6df1416a3cc684c9bbe2819c17a Mon Sep 17 00:00:00 2001 From: MichalObi Date: Tue, 9 Feb 2021 19:35:53 +0100 Subject: [PATCH] Merge sheets and groups / add log wrapper --- FE/simple-sheet-fe/src/App.js | 78 ++++++++++++++++++++--------------- 1 file changed, 44 insertions(+), 34 deletions(-) diff --git a/FE/simple-sheet-fe/src/App.js b/FE/simple-sheet-fe/src/App.js index bb25434..06aef5f 100644 --- a/FE/simple-sheet-fe/src/App.js +++ b/FE/simple-sheet-fe/src/App.js @@ -3,45 +3,55 @@ import logo from './logo.svg'; import './App.css'; function App() { - const [error, setError] = useState(null), - [isLoaded, setIsLoaded] = useState(false), - [items, setItems] = useState([]), - handleAjaxError = error => { + const useStateCallbackWrapper = (initilValue, callBack) => { + const [state, setState] = useState(initilValue); + + useEffect(() => callBack(state), [state]); + return [state, setState]; + }; + + const log = (key, state) => console.log(`${key}`, state); + + const [error, setError] = useStateCallbackWrapper(null, state => log('error', state)), + [isLoaded, setIsLoaded] = useStateCallbackWrapper(false, state => log('isLoaded', state)), + [sheetsAndGroups, setSheetsAndGroups] = useStateCallbackWrapper({}, state => log('sheetsAndGroups', state)); + + const handleAjaxError = error => { setIsLoaded(true); setError(error); - - console.log('err', error); }; - useEffect(() => { - fetch('/sheets/1') - .then(res => res.json()) - .then( - res => { - console.log('sheets', res); - - fetch(`/groups/${res.id}`) - .then(res => res.json()) - .then(res => { - setIsLoaded(true); - console.log('groups', res); - }, handleAjaxError) + useEffect(() => { + fetch('/sheets/1') + .then(sheets => sheets.json()) + .then(sheets => { + if (sheets) { + fetch(`/groups/${sheets.id}`) + .then(groups => groups.json()) + .then(groups => { + const sheetsAndGroups = Object.assign({}, sheets, groups); + delete sheetsAndGroups.id; + + setSheetsAndGroups(sheetsAndGroups); + setIsLoaded(true); }, handleAjaxError) - }, []); - - if (error) { - return

error

; - } else if (!isLoaded) { - return

loading

; - } else { - return ( -
-
- Simple Sheet -
-
- ); - } + } + }, handleAjaxError) + }, []); + + if (error) { + return

error

; + } else if (!isLoaded) { + return

loading

; + } else { + return ( +
+
+ Simple Sheet +
+
+ ); + } } export default App;