diff --git a/README.md b/README.md index 487c428..4e202ca 100644 --- a/README.md +++ b/README.md @@ -1,43 +1,43 @@ -# React Dev Test Assignment ⚛️ - -https://user-images.githubusercontent.com/12231393/136546219-a49c6ea7-fd63-48b5-8906-04ce8c04a181.mp4 - -## Description -Try to finish as much TODO's as possible. These are found within the React app codebase. When you view the `/src` folder you will find an application for users that want to create their own addressbook (also shown in the video above). But as mentioned before there are some TODO's to be completed in order to make the application work as expected. - -In order to start this assignment you need to: -- ⬇️ Clone this repository -- 🌲 Create a separate branch called `feat/todo-assignment` -- 👨‍💻 Open up your preferred editor (mine is VS Code) -- 🏃🏻‍♂️ Run `npm install` and then `npm start` -- 🔎 Search for all `TODO:` strings within the `/src` folder and start building! - -> Note: You will find some Bonus TODO's. These are not mandatory for completing this assignment. Feel free to flex your programming skills 💪 - -## TODO's -Here is a list of all the TODO's to make life a bit easier: - -### Styling -- [ ] Add the 'Roboto' font from Google fonts and add it as a global CSS var called `--font-primary`. -- [ ] Make application responsive. It is already for the most part, but it is not optimal for smaller screens. -- [ ] Create separate styles for .primary and .secondary variants of the button component. - -### React -- [ ] Write a custom hook to set form fields in a more generic way. -- [ ] Fetch addresses based on houseNumber and zipCode. -- [ ] Create generic `
` component to display form rows, legend and a submit button. -- [ ] Create an `` component for displaying an error message. -- [ ] Add a button to clear all form fields. Button must look different from the default primary button, see design. -- [ ] Add conditional classNames for `primary` and `secondary` variant in ` - - - {addresses.length > 0 && - addresses.map((address) => { - return ( - -
- - ); - })} - {/* TODO: Create generic
component to display form rows, legend and a submit button */} - {selectedAddress && ( - -
- ✏️ Add personal info to address -
- -
-
- -
- -
-
- )} - - {/* TODO: Create an component for displaying an error message */} - {error &&
{error}
} - - {/* TODO: Add a button to clear all form fields. Button must look different from the default primary button, see design. */} - - -
- -
- - ); -} - -export default App; +import React from "react"; + +import Address from "./ui/components/Address/Address"; +import AddressBook from "./ui/components/AddressBook/AddressBook"; +import Button from "./ui/components/Button/Button"; +import Radio from "./ui/components/Radio/Radio"; +import Section from "./ui/components/Section/Section"; +import transformAddress from "./core/models/address"; +import useAddressBook from "./ui/hooks/useAddressBook"; + +import "./App.css"; +import { fetchAddress } from "./core/services/databaseService"; +import ErrorMessage from "./ui/components/ErrorMessage/ErrorMessage"; +import Form from "./ui/components/Form/Form"; +import FormItem from "./ui/components/FormItem/FormItem"; +import useFormFields from "./ui/hooks/setFields"; + +function App() { + const [ + { zipCode, houseNumber, firstName, lastName, selectedAddress }, + handleFieldChange, + resetFields, + ] = useFormFields({ + zipCode: "", + houseNumber: "", + firstName: "", + lastName: "", + selectedAddress: "", + }); + const [loading, setLoading] = React.useState(false); + /** + * Results states + */ + const [error, setError] = React.useState(""); + const [addresses, setAddresses] = React.useState([]); + /** + * Redux actions + */ + const { addAddress } = useAddressBook(); + + /** + * Text fields onChange handlers + */ + + const handleClearFields = (e) => { + setAddresses([]); + resetFields(); + }; + + const handleAddressSubmit = async (e) => { + setLoading(true); + e.preventDefault(); + + try { + const addresses = await fetchAddress({ + zipCode: e.target.zipCode.value, + houseNumber: e.target.houseNumber.value, + }); + + if (addresses.status === "error") { + setError(addresses.errormessage); + setLoading(false); + return; + } + + setAddresses((prevAddresses) => [ + ...addresses.details.map((address) => { + return transformAddress(address); + }), + ...prevAddresses, + ]); + } catch (error) { + setError(error.message); + } + + setError(); + e.preventDefault(); + setLoading(false); + }; + + const handlePersonSubmit = (e) => { + e.preventDefault(); + + if (!selectedAddress || !addresses.length) { + setError( + "No address selected, try to select an address or find one if you haven't" + ); + return; + } + + const foundAddress = addresses.find( + (address) => address.id === selectedAddress + ); + + addAddress({ ...foundAddress, firstName, lastName }); + }; + + return ( +
+
+

+ Create your own address book! +
+ + Enter an address by zipcode add personal info and + done! 👏 + +

+
+ + + + {addresses.length > 0 && + addresses.map((address) => { + return ( + +
+ + ); + })} + {selectedAddress && ( +
+ + + + )} +
+
+ +
+
+ ); +} + +export default App; diff --git a/src/App.test.js b/src/App.test.js index 1f03afe..4de7037 100644 --- a/src/App.test.js +++ b/src/App.test.js @@ -1,8 +1,8 @@ -import { render, screen } from '@testing-library/react'; -import App from './App'; - -test('renders learn react link', () => { - render(); - const linkElement = screen.getByText(/learn react/i); - expect(linkElement).toBeInTheDocument(); -}); +import { render, screen } from '@testing-library/react'; +import App from './App'; + +test('renders learn react link', () => { + render(); + const linkElement = screen.getByText(/learn react/i); + expect(linkElement).toBeInTheDocument(); +}); diff --git a/src/assets/fonts/Roboto/LICENSE.txt b/src/assets/fonts/Roboto/LICENSE.txt new file mode 100644 index 0000000..75b5248 --- /dev/null +++ b/src/assets/fonts/Roboto/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/assets/fonts/Roboto/Roboto-Regular.ttf b/src/assets/fonts/Roboto/Roboto-Regular.ttf new file mode 100644 index 0000000..ddf4bfa Binary files /dev/null and b/src/assets/fonts/Roboto/Roboto-Regular.ttf differ diff --git a/src/core/models/address.js b/src/core/models/address.js index 522e214..fe8a2cd 100644 --- a/src/core/models/address.js +++ b/src/core/models/address.js @@ -1,13 +1,21 @@ -export default function transformAddress(data) { - const { firstName, lastName, city, houseNumber, lat, lon, postcode, street } = - data; - return { - city: city || "", - firstName: firstName || "", - houseNumber: houseNumber || "", - id: `${lat || Date.now()}_${lon || Math.random()}`, - lastName: lastName || "", - postcode: postcode || "", - street: street || "", - }; -} +export default function transformAddress(data) { + const { + firstName, + lastName, + city, + houseNumber, + lat, + lon, + postcode, + street, + } = data; + return { + city: city || "", + firstName: firstName || "", + houseNumber: houseNumber || "", + id: `${lat || Date.now()}_${lon || Math.random()}`, + lastName: lastName || "", + postcode: postcode || "", + street: street || "", + }; +} diff --git a/src/core/reducers/addressBook.js b/src/core/reducers/addressBook.js index 6d3980a..72437ea 100644 --- a/src/core/reducers/addressBook.js +++ b/src/core/reducers/addressBook.js @@ -1,21 +1,35 @@ -const defaultState = { - addresses: [], -}; - -const reducer = (state = defaultState, action) => { - switch (action.type) { - case "address/add": - /** TODO: Prevent duplicate addresses */ - return { ...state, addresses: [...state.addresses, action.payload] }; - case "address/remove": - /** TODO: Write a state update which removes an address from the addresses array. */ - return state; - case "addresses/add": { - return { ...state, addresses: action.payload }; - } - default: - return state; - } -}; - -export default reducer; +const defaultState = { + addresses: [], +}; + +const reducer = (state = defaultState, action) => { + switch (action.type) { + case "address/add": + if ( + state.addresses.find( + (address) => address.id === action.payload.id + ) + ) { + return state; + } + + return { + ...state, + addresses: [...state.addresses, action.payload], + }; + case "address/remove": + return { + ...state, + addresses: state.addresses.filter( + (item) => item.id !== action.payload + ), + }; + case "addresses/add": { + return { ...state, addresses: action.payload }; + } + default: + return state; + } +}; + +export default reducer; diff --git a/src/core/reducers/index.js b/src/core/reducers/index.js index d03190d..2109855 100644 --- a/src/core/reducers/index.js +++ b/src/core/reducers/index.js @@ -1,22 +1,22 @@ -import { applyMiddleware, combineReducers, compose, createStore } from "redux"; - -import addressBook from "./addressBook"; - -export const rootReducer = combineReducers({ addressBook }); - -export const configureStore = () => { - const middlewareEnhancer = applyMiddleware(); - - let composedEnhancers = compose(middlewareEnhancer); - - /** Don't add Redux devtools on production. */ - if (typeof window.__REDUX_DEVTOOLS_EXTENSION__ === "function") { - composedEnhancers = compose( - middlewareEnhancer, - // eslint-disable-next-line no-underscore-dangle - window.__REDUX_DEVTOOLS_EXTENSION__() - ); - } - - return createStore(rootReducer, {}, composedEnhancers); -}; +import { applyMiddleware, combineReducers, compose, createStore } from "redux"; + +import addressBook from "./addressBook"; + +export const rootReducer = combineReducers({ addressBook }); + +export const configureStore = () => { + const middlewareEnhancer = applyMiddleware(); + + let composedEnhancers = compose(middlewareEnhancer); + + /** Don't add Redux devtools on production. */ + if (typeof window.__REDUX_DEVTOOLS_EXTENSION__ === "function") { + composedEnhancers = compose( + middlewareEnhancer, + // eslint-disable-next-line no-underscore-dangle + window.__REDUX_DEVTOOLS_EXTENSION__() + ); + } + + return createStore(rootReducer, {}, composedEnhancers); +}; diff --git a/src/core/services/databaseService.js b/src/core/services/databaseService.js index 6d32a06..9ab85ef 100644 --- a/src/core/services/databaseService.js +++ b/src/core/services/databaseService.js @@ -1,7 +1,19 @@ -import localforage from "localforage"; - -const database = localforage.createInstance({ - name: "address-book", -}); - -export default database; +import localforage from "localforage"; + +const database = localforage.createInstance({ + name: "address-book", +}); + +export const fetchAddress = async ({ houseNumber, zipCode }) => { + try { + const response = await fetch( + `http://api.postcodedata.nl/v1/postcode/?postcode=${zipCode}&streetnumber=${houseNumber}&ref=domeinnaam.nl&type=json` + ).then((response) => response.json()); + + return response; + } catch (err) { + return Promise.reject(err); + } +}; + +export default database; diff --git a/src/index.css b/src/index.css index ec2585e..bd5bd6d 100644 --- a/src/index.css +++ b/src/index.css @@ -1,13 +1,13 @@ -body { - margin: 0; - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', - 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', - sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; -} - -code { - font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', - monospace; -} +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +code { + font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', + monospace; +} diff --git a/src/index.js b/src/index.js index 0c381f3..691b07b 100644 --- a/src/index.js +++ b/src/index.js @@ -1,23 +1,23 @@ -import React from "react"; -import ReactDOM from "react-dom"; -import { Provider } from "react-redux"; - -import "./index.css"; - -import App from "./App"; -import { configureStore } from "./core/reducers"; -import reportWebVitals from "./reportWebVitals"; - -ReactDOM.render( - - - - - , - document.getElementById("root") -); - -// If you want to start measuring performance in your app, pass a function -// to log results (for example: reportWebVitals(console.log)) -// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals -reportWebVitals(); +import React from "react"; +import ReactDOM from "react-dom"; +import { Provider } from "react-redux"; + +import "./index.css"; + +import App from "./App"; +import { configureStore } from "./core/reducers"; +import reportWebVitals from "./reportWebVitals"; + +ReactDOM.render( + + + + + , + document.getElementById("root") +); + +// If you want to start measuring performance in your app, pass a function +// to log results (for example: reportWebVitals(console.log)) +// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals +reportWebVitals(); diff --git a/src/reportWebVitals.js b/src/reportWebVitals.js index 5253d3a..77957db 100644 --- a/src/reportWebVitals.js +++ b/src/reportWebVitals.js @@ -1,13 +1,13 @@ -const reportWebVitals = onPerfEntry => { - if (onPerfEntry && onPerfEntry instanceof Function) { - import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { - getCLS(onPerfEntry); - getFID(onPerfEntry); - getFCP(onPerfEntry); - getLCP(onPerfEntry); - getTTFB(onPerfEntry); - }); - } -}; - -export default reportWebVitals; +const reportWebVitals = onPerfEntry => { + if (onPerfEntry && onPerfEntry instanceof Function) { + import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { + getCLS(onPerfEntry); + getFID(onPerfEntry); + getFCP(onPerfEntry); + getLCP(onPerfEntry); + getTTFB(onPerfEntry); + }); + } +}; + +export default reportWebVitals; diff --git a/src/setupTests.js b/src/setupTests.js index 8f2609b..141e479 100644 --- a/src/setupTests.js +++ b/src/setupTests.js @@ -1,5 +1,5 @@ -// jest-dom adds custom jest matchers for asserting on DOM nodes. -// allows you to do things like: -// expect(element).toHaveTextContent(/react/i) -// learn more: https://github.com/testing-library/jest-dom -import '@testing-library/jest-dom'; +// jest-dom adds custom jest matchers for asserting on DOM nodes. +// allows you to do things like: +// expect(element).toHaveTextContent(/react/i) +// learn more: https://github.com/testing-library/jest-dom +import '@testing-library/jest-dom'; diff --git a/src/ui/components/Address/Address.js b/src/ui/components/Address/Address.js index fcf32fe..bbdece3 100644 --- a/src/ui/components/Address/Address.js +++ b/src/ui/components/Address/Address.js @@ -1,13 +1,14 @@ -import React from "react"; - -import $ from "./Address.module.css"; - -const Address = ({ address }) => { - return ( -
- {address.street} {address.houseNumber}, {address.postcode}, {address.city} -
- ); -}; - -export default Address; +import React from "react"; + +import $ from "./Address.module.css"; + +const Address = ({ address }) => { + return ( +
+ {address.street} {address.houseNumber}, {address.postcode},{" "} + {address.city} +
+ ); +}; + +export default Address; diff --git a/src/ui/components/Address/Address.module.css b/src/ui/components/Address/Address.module.css index 9c6f57f..1bb10bb 100644 --- a/src/ui/components/Address/Address.module.css +++ b/src/ui/components/Address/Address.module.css @@ -1,3 +1,3 @@ -.address { - color: var(--color-text); -} +.address { + color: var(--color-text); +} diff --git a/src/ui/components/AddressBook/AddressBook.js b/src/ui/components/AddressBook/AddressBook.js index faafd75..31b58e5 100644 --- a/src/ui/components/AddressBook/AddressBook.js +++ b/src/ui/components/AddressBook/AddressBook.js @@ -1,54 +1,62 @@ -import React from "react"; -import { useSelector } from "react-redux"; - -import Address from "../Address/Address"; -import Button from "../Button/Button"; -import Card from "../Card/Card"; -import useAddressBook from "../../hooks/useAddressBook"; - -import $ from "./AddressBook.module.css"; - -const AddressBook = () => { - const addresses = useSelector((state) => state.addressBook.addresses); - const { removeAddress, loadSavedAddresses, loading } = useAddressBook(); - - React.useEffect(() => { - loadSavedAddresses(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - return ( -
-

📓 Address book ({addresses.length})

- {!loading && ( - <> - {addresses.length === 0 &&

No addresses found, try add one 😉

} - {addresses.map((address) => { - return ( - -
-
-

- {address.firstName} {address.lastName} -

-
-
-
- -
-
-
- ); - })} - - )} -
- ); -}; - -export default AddressBook; +import React from "react"; +import { useSelector } from "react-redux"; + +import Address from "../Address/Address"; +import Button from "../Button/Button"; +import Card from "../Card/Card"; +import useAddressBook from "../../hooks/useAddressBook"; + +import $ from "./AddressBook.module.css"; + +const AddressBook = () => { + const addresses = useSelector( + (state) => state.addressBook.addresses + ); + console.log(addresses); + const { removeAddress, loadSavedAddresses, loading } = + useAddressBook(); + + React.useEffect(() => { + loadSavedAddresses(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + return ( +
+

📓 Address book ({addresses.length})

+ {!loading && ( + <> + {addresses.length === 0 && ( +

No addresses found, try add one 😉

+ )} + {addresses.map((address) => { + return ( + +
+
+

+ {address.firstName}{" "} + {address.lastName} +

+
+
+
+
+
+
+ ); + })} + + )} +
+ ); +}; + +export default AddressBook; diff --git a/src/ui/components/AddressBook/AddressBook.module.css b/src/ui/components/AddressBook/AddressBook.module.css index 5032bf3..36b7498 100644 --- a/src/ui/components/AddressBook/AddressBook.module.css +++ b/src/ui/components/AddressBook/AddressBook.module.css @@ -1,24 +1,38 @@ -.addressBook { - display: flex; - flex-direction: column; - gap: 1rem; -} - -.remove { - --color-brand: var(--color-accent); - margin-left: auto; -} - -.item { - align-items: center; - display: flex; - gap: 1rem; -} - -.item address { - font-size: 0.85em; -} - -.item h3 { - margin: 0 0 0.5em; -} +.addressBook { + display: flex; + flex-direction: column; + gap: 1rem; +} + +.item { + align-items: flex-start; + display: flex; + flex-direction: column; + gap: 1rem; +} + +.item address { + font-size: 0.85em; +} + +.item h3 { + margin: 0 0 0.5em; +} + +.addressBook > h2 { + font-size: 18px; +} +@media (min-width: 428px) { + .addressBook > h2 { + font-size: 27px; + } +} +@media (min-width: 428px) { + .addressBook > h2 { + font-size: 27px; + } + .item { + align-items: center; + flex-direction: row; + } +} diff --git a/src/ui/components/Button/Button.js b/src/ui/components/Button/Button.js index dc73e26..057ea64 100644 --- a/src/ui/components/Button/Button.js +++ b/src/ui/components/Button/Button.js @@ -1,26 +1,40 @@ -import React from "react"; -import cx from "classnames"; - -import $ from "./Button.module.css"; - -const Button = ({ - children, - onClick, - type = "button", - variant = "primary", // or 'secondary' -}) => { - return ( - - ); -}; - -export default Button; +import React from "react"; + +import $ from "./Button.module.css"; + +const Button = ({ + children, + onClick, + type = "button", + variant = "primary", + loading, + text, +}) => { + let buttonClassName; + + switch (variant) { + case "primary": + buttonClassName = $.primary; + break; + case "secondary": + buttonClassName = $.secondary; + break; + case "remove": + buttonClassName = $.remove; + break; + default: + break; + } + + return ( + + ); +}; + +export default Button; diff --git a/src/ui/components/Button/Button.module.css b/src/ui/components/Button/Button.module.css index c10325a..a6eaabf 100644 --- a/src/ui/components/Button/Button.module.css +++ b/src/ui/components/Button/Button.module.css @@ -1,25 +1,38 @@ -.button { - border-radius: var(--border-radius-default); - box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1); - color: white; - cursor: pointer; - font-size: 0.9em; - font-weight: bold; - max-width: var(--width-input); - padding: 0.5em 1em; - margin: 0.5em 0; - transition: transform 0.1s ease; - width: 100%; -} - -.button:hover { - transform: scale(1.05); -} - -.button:active { - transform: scale(0.95); -} - -/** TODO: Create separate styles for .primary and .secondary variants of this button: -* - Must use the CSS variables declared in App.css -*/ +.button { + border-radius: var(--border-radius-default); + box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.1); + cursor: pointer; + font-size: 0.9em; + font-weight: bold; + max-width: var(--width-input); + padding: 0.5em 1em; + margin: 0.5em 0; + transition: transform 0.1s ease; + width: 100%; +} + +.button:hover { + transform: scale(1.05); +} + +.button:active { + transform: scale(0.95); +} + +.primary { + background-color: var(--color-brand); + color: var(--color-background); + border: 0; +} + +.secondary { + background-color: var(--color-background); + color: var(--color-brand); + border: 1px solid var(--color-brand); +} + +.remove { + background-color: var(--color-background); + color: var(--color-accent); + border: 1px solid var(--color-accent); +} diff --git a/src/ui/components/Card/Card.js b/src/ui/components/Card/Card.js index 812b393..3e19b63 100644 --- a/src/ui/components/Card/Card.js +++ b/src/ui/components/Card/Card.js @@ -1,9 +1,9 @@ -import React from "react"; - -import $ from "./Card.module.css"; - -const Card = ({ children }) => { - return
{children}
; -}; - -export default Card; +import React from "react"; + +import $ from "./Card.module.css"; + +const Card = ({ children }) => { + return
{children}
; +}; + +export default Card; diff --git a/src/ui/components/Card/Card.module.css b/src/ui/components/Card/Card.module.css index 4a7ceb5..6cf236c 100644 --- a/src/ui/components/Card/Card.module.css +++ b/src/ui/components/Card/Card.module.css @@ -1,7 +1,7 @@ -.card { - padding: 1rem; - background: var(--color-background); - border-radius: var(--border-radius-default); - box-shadow: 0 10px 15px rgba(0, 0, 0, 0.15); - border-left: 4px solid var(--color-accent); -} +.card { + padding: 1rem; + background: var(--color-background); + border-radius: var(--border-radius-default); + box-shadow: 0 10px 15px rgba(0, 0, 0, 0.15); + border-left: 4px solid var(--color-accent); +} diff --git a/src/ui/components/ErrorMessage/ErrorMessage.js b/src/ui/components/ErrorMessage/ErrorMessage.js new file mode 100644 index 0000000..22d3e51 --- /dev/null +++ b/src/ui/components/ErrorMessage/ErrorMessage.js @@ -0,0 +1,13 @@ +import React from "react"; + +import $ from "./ErrorMessage.module.css"; + +const ErrorMessage = ({ message }) => { + return ( +
+

{message}

+
+ ); +}; + +export default ErrorMessage; diff --git a/src/ui/components/ErrorMessage/ErrorMessage.module.css b/src/ui/components/ErrorMessage/ErrorMessage.module.css new file mode 100644 index 0000000..6ea3892 --- /dev/null +++ b/src/ui/components/ErrorMessage/ErrorMessage.module.css @@ -0,0 +1,4 @@ +.ErrorMessage { + color: red; + padding: 0.5em 0; +} diff --git a/src/ui/components/Form/Form.js b/src/ui/components/Form/Form.js new file mode 100644 index 0000000..deeb1ee --- /dev/null +++ b/src/ui/components/Form/Form.js @@ -0,0 +1,27 @@ +import React from "react"; +import Button from "../Button/Button"; + +const Form = ({ + onSubmit, + buttonText, + legend, + buttonLoading, + children, +}) => { + return ( + <> +
+
+ {legend && {legend}} {children} +
+
+ + ); +}; + +export default Form; diff --git a/src/ui/components/Form/Form.module.css b/src/ui/components/Form/Form.module.css new file mode 100644 index 0000000..6cf236c --- /dev/null +++ b/src/ui/components/Form/Form.module.css @@ -0,0 +1,7 @@ +.card { + padding: 1rem; + background: var(--color-background); + border-radius: var(--border-radius-default); + box-shadow: 0 10px 15px rgba(0, 0, 0, 0.15); + border-left: 4px solid var(--color-accent); +} diff --git a/src/ui/components/FormItem/FormItem.js b/src/ui/components/FormItem/FormItem.js new file mode 100644 index 0000000..d70cedc --- /dev/null +++ b/src/ui/components/FormItem/FormItem.js @@ -0,0 +1,20 @@ +import $ from "./FormItem.module.css"; +import InputText from "../InputText/InputText"; + +export default function FormItem({ + value, + onChange, + placeholder, + name, +}) { + return ( +
+ +
+ ); +} diff --git a/src/ui/components/FormItem/FormItem.module.css b/src/ui/components/FormItem/FormItem.module.css new file mode 100644 index 0000000..1b1a457 --- /dev/null +++ b/src/ui/components/FormItem/FormItem.module.css @@ -0,0 +1,3 @@ +.formItem { + margin-bottom: 0.5em; +} diff --git a/src/ui/components/InputText/InputText.js b/src/ui/components/InputText/InputText.js index 0324204..f6e7679 100644 --- a/src/ui/components/InputText/InputText.js +++ b/src/ui/components/InputText/InputText.js @@ -1,18 +1,18 @@ -import React from "react"; - -import $ from "./InputText.module.css"; - -const InputText = ({ name, onChange, placeholder, value }) => { - return ( - - ); -}; - -export default InputText; +import React from "react"; + +import $ from "./InputText.module.css"; + +const InputText = ({ name, onChange, placeholder, value }) => { + return ( + + ); +}; + +export default InputText; diff --git a/src/ui/components/InputText/InputText.module.css b/src/ui/components/InputText/InputText.module.css index caf0d21..dfad0b0 100644 --- a/src/ui/components/InputText/InputText.module.css +++ b/src/ui/components/InputText/InputText.module.css @@ -1,9 +1,9 @@ -.inputText { - background: var(--color-background); - border-radius: var(--border-radius-default); - border: 1px solid var(--color-border); - font-size: inherit; - max-width: var(--width-input); - padding: 0.5em; - width: 100%; -} +.inputText { + background: var(--color-background); + border-radius: var(--border-radius-default); + border: 1px solid var(--color-border); + font-size: inherit; + max-width: var(--width-input); + padding: 0.5em; + width: 100%; +} diff --git a/src/ui/components/Radio/Radio.js b/src/ui/components/Radio/Radio.js index ad31c7f..29fff65 100644 --- a/src/ui/components/Radio/Radio.js +++ b/src/ui/components/Radio/Radio.js @@ -1,14 +1,14 @@ -import React from "react"; - -import $ from "./Radio.module.css"; - -const Radio = ({ children, id, name, onChange }) => { - return ( -
- - -
- ); -}; - -export default Radio; +import React from "react"; + +import $ from "./Radio.module.css"; + +const Radio = ({ children, id, name, onChange }) => { + return ( +
+ + +
+ ); +}; + +export default Radio; diff --git a/src/ui/components/Radio/Radio.module.css b/src/ui/components/Radio/Radio.module.css index 5735339..4c3b2a1 100644 --- a/src/ui/components/Radio/Radio.module.css +++ b/src/ui/components/Radio/Radio.module.css @@ -1,20 +1,20 @@ -.radio { - align-items: center; - border-radius: var(--border-radius-default); - border: 1px solid var(--color-brand); - cursor: pointer; - display: flex; - gap: 1rem; - margin: 1rem 0; - max-width: var(--width-input); - padding: 1em; - width: 100%; -} - -.radio:hover { - background: var(--color-accent); -} - -.radio input[type="radio"] { - margin: 0; -} +.radio { + align-items: center; + border-radius: var(--border-radius-default); + border: 1px solid var(--color-brand); + cursor: pointer; + display: flex; + gap: 1rem; + margin: 1rem 0; + max-width: var(--width-input); + padding: 1em; + width: 100%; +} + +.radio:hover { + background: var(--color-accent); +} + +.radio input[type="radio"] { + margin: 0; +} diff --git a/src/ui/components/Section/Section.js b/src/ui/components/Section/Section.js index 319465e..255af8a 100644 --- a/src/ui/components/Section/Section.js +++ b/src/ui/components/Section/Section.js @@ -1,19 +1,19 @@ -import React from "react"; -import cx from "classnames"; - -import $ from "./Section.module.css"; - -const Section = ({ children, variant = "light" }) => { - return ( -
- {children} -
- ); -}; - -export default Section; +import React from "react"; +import cx from "classnames"; + +import $ from "./Section.module.css"; + +const Section = ({ children, variant = "light" }) => { + return ( +
+ {children} +
+ ); +}; + +export default Section; diff --git a/src/ui/components/Section/Section.module.css b/src/ui/components/Section/Section.module.css index 1b2298a..35233fa 100644 --- a/src/ui/components/Section/Section.module.css +++ b/src/ui/components/Section/Section.module.css @@ -1,16 +1,16 @@ -.section { - background-color: var(--color-background); - border-radius: var(--border-radius-xl); - box-shadow: 0 15px 15px rgba(0, 0, 0, 0.15); - color: var(--color-text); - margin: 3rem auto; - max-width: var(--width-content); - padding: 2rem 3rem; - width: 100%; -} - -.dark { - --color-background: #141925; - --color-text: #fff; - --color-text-light: #878b9a; -} +.section { + background-color: var(--color-background); + border-radius: var(--border-radius-xl); + box-shadow: 0 15px 15px rgba(0, 0, 0, 0.15); + color: var(--color-text); + margin: 3rem auto; + max-width: var(--width-content); + padding: 2rem 3rem; + width: 100%; +} + +.dark { + --color-background: #141925; + --color-text: #fff; + --color-text-light: #878b9a; +} diff --git a/src/ui/hooks/setFields.js b/src/ui/hooks/setFields.js new file mode 100644 index 0000000..27cdc13 --- /dev/null +++ b/src/ui/hooks/setFields.js @@ -0,0 +1,21 @@ +import { useState } from "react"; + +function useFormFields(initialState) { + const [fields, setFields] = useState(initialState); + + function handleFieldChange(event) { + setFields({ + ...fields, + [event.target.name]: + event.target.value || event.target.checked, + }); + } + + function resetFields() { + setFields(initialState); + } + + return [fields, handleFieldChange, resetFields]; +} + +export default useFormFields; diff --git a/src/ui/hooks/useAddressBook.js b/src/ui/hooks/useAddressBook.js index 4f698a1..a01085a 100644 --- a/src/ui/hooks/useAddressBook.js +++ b/src/ui/hooks/useAddressBook.js @@ -1,44 +1,44 @@ -import React from "react"; -import { useDispatch, useStore } from "react-redux"; - -import transformAddress from "../../core/models/address"; -import databaseService from "../../core/services/databaseService"; - -export default function useAddressBook() { - const dispatch = useDispatch(); - const store = useStore(); - const [loading, setLoading] = React.useState(true); - - const updateDatabase = React.useCallback(() => { - const state = store.getState(); - databaseService.setItem("addresses", state.addressBook.addresses); - }, [store]); - - return { - /** Add address to the redux store */ - addAddress: (address) => { - dispatch({ type: "address/add", payload: address }); - updateDatabase(); - }, - /** Remove address by ID from the redux store */ - removeAddress: (id) => { - dispatch({ type: "address/remove", payload: id }); - updateDatabase(); - }, - /** Loads saved addresses from the indexedDB */ - loadSavedAddresses: async () => { - const saved = await databaseService.getItem("addresses"); - // No saved item found, exit this function - if (!saved || !Array.isArray(saved)) { - setLoading(false); - return; - } - dispatch({ - type: "addresses/add", - payload: saved.map((address) => transformAddress(address)), - }); - setLoading(false); - }, - loading, - }; -} +import React from "react"; +import { useDispatch, useStore } from "react-redux"; + +import transformAddress from "../../core/models/address"; +import databaseService from "../../core/services/databaseService"; + +export default function useAddressBook() { + const dispatch = useDispatch(); + const store = useStore(); + const [loading, setLoading] = React.useState(true); + + const updateDatabase = React.useCallback(() => { + const state = store.getState(); + databaseService.setItem("addresses", state.addressBook.addresses); + }, [store]); + + return { + /** Add address to the redux store */ + addAddress: (address) => { + dispatch({ type: "address/add", payload: address }); + updateDatabase(); + }, + /** Remove address by ID from the redux store */ + removeAddress: (id) => { + dispatch({ type: "address/remove", payload: id }); + updateDatabase(); + }, + /** Loads saved addresses from the indexedDB */ + loadSavedAddresses: async () => { + const saved = await databaseService.getItem("addresses"); + // No saved item found, exit this function + if (!saved || !Array.isArray(saved)) { + setLoading(false); + return; + } + dispatch({ + type: "addresses/add", + payload: saved.map((address) => transformAddress(address)), + }); + setLoading(false); + }, + loading, + }; +}