Skip to content

Commit

Permalink
feat: Exercise: Refactor dispatch methods to meaningful abstractions …
Browse files Browse the repository at this point in the history
…inside the context
  • Loading branch information
Param-Harrison committed Apr 19, 2020
1 parent 3efe261 commit 9d9ed28
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 8 deletions.
12 changes: 6 additions & 6 deletions src/components/global-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,16 @@ export const useGlobalStore = () => {
const GlobalProvider = ({ children }) => {
const [contacts, dispatch] = useContacts();

const removeContact = (id) => {
dispatch({ type: "REMOVE_CONTACT", payload: { id } });
const addContact = (payload) => {
dispatch({ type: "ADD_CONTACT", payload });
};

const editContact = (contact) => {
dispatch({ type: "EDIT_CONTACT", payload: contact });
const editContact = (payload) => {
dispatch({ type: "EDIT_CONTACT", payload });
};

const addContact = (contact) => {
dispatch({ type: "ADD_CONTACT", payload: contact });
const removeContact = (id) => {
dispatch({ type: "REMOVE_CONTACT", payload: { id } });
};

return (
Expand Down
4 changes: 2 additions & 2 deletions src/components/use-contacts-storage.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ const useContactsStorage = ({ key, contacts, dispatch }) => {
// Initial contacts loaded from localStorage
useEffect(() => {
if (localStorage.getItem(key)) {
const localContacts = JSON.parse(localStorage.getItem(key));
dispatch({ type: "INIT", payload: localContacts });
const payload = JSON.parse(localStorage.getItem(key));
dispatch({ type: "INIT", payload });
}
}, [key, dispatch]); // Load only once after the component mounts

Expand Down
1 change: 1 addition & 0 deletions src/components/use-contacts.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const reducer = (state, action) => {

const useContacts = () => {
const [contacts, dispatch] = useReducer(reducer, []);

// Save and retrieve happens here
useContactsStorage({ key: "contacts", contacts, dispatch });

Expand Down

0 comments on commit 9d9ed28

Please sign in to comment.