| import { Box, Button, Paper, TextField } from '@mui/material'; | import { Box, Button, Paper, TextField } from '@mui/material'; | ||||
| import { useFormik } from 'formik'; | import { useFormik } from 'formik'; | ||||
| import { useSession } from 'next-auth/react'; | |||||
| import { useRouter } from 'next/router'; | import { useRouter } from 'next/router'; | ||||
| import PropType from 'prop-types'; | import PropType from 'prop-types'; | ||||
| import { useState } from 'react'; | import { useState } from 'react'; | ||||
| import { shippingDetailsSchema } from '../../../schemas/shippingDetailsSchema'; | import { shippingDetailsSchema } from '../../../schemas/shippingDetailsSchema'; | ||||
| import { useUserData } from '../../../store/user-context'; | |||||
| import ErrorMessageComponent from '../../mui/ErrorMessageComponent'; | import ErrorMessageComponent from '../../mui/ErrorMessageComponent'; | ||||
| const ShippingDetailsForm = ({ | const ShippingDetailsForm = ({ | ||||
| enableBtn = true, | enableBtn = true, | ||||
| }) => { | }) => { | ||||
| const [error] = useState({ hasError: false, errorMessage: '' }); | const [error] = useState({ hasError: false, errorMessage: '' }); | ||||
| const { data: session } = useSession(); | |||||
| const { userStorage } = useUserData(); | |||||
| const router = useRouter(); | const router = useRouter(); | ||||
| const formikSubmitHandler = async (values) => { | const formikSubmitHandler = async (values) => { | ||||
| const formik = useFormik({ | const formik = useFormik({ | ||||
| initialValues: { | initialValues: { | ||||
| fullName: session?.user ? session.user.fullName : '', | |||||
| address: session?.user ? session.user.address : '', | |||||
| address2: session?.user ? session.user.address2 : '', | |||||
| city: session?.user ? session.user.city : '', | |||||
| country: session?.user ? session.user.country : '', | |||||
| postcode: session?.user ? session.user.postcode : '', | |||||
| fullName: userStorage ? userStorage.fullName : '', | |||||
| address: userStorage ? userStorage.address : '', | |||||
| address2: userStorage ? userStorage.address2 : '', | |||||
| city: userStorage ? userStorage.city : '', | |||||
| country: userStorage ? userStorage.country : '', | |||||
| postcode: userStorage ? userStorage.postcode : '', | |||||
| }, | }, | ||||
| validationSchema: shippingDetailsSchema, | validationSchema: shippingDetailsSchema, | ||||
| onSubmit: formikSubmitHandler, | onSubmit: formikSubmitHandler, |
| PROFILE_PAGE, | PROFILE_PAGE, | ||||
| } from '../../../constants/pages'; | } from '../../../constants/pages'; | ||||
| import { useStore } from '../../../store/cart-context'; | import { useStore } from '../../../store/cart-context'; | ||||
| import { useUserUpdate } from '../../../store/user-context'; | |||||
| const Navbar = () => { | const Navbar = () => { | ||||
| const router = useRouter(); | const router = useRouter(); | ||||
| const { totalQuantity } = useStore(); | const { totalQuantity } = useStore(); | ||||
| const { data: session } = useSession(); | const { data: session } = useSession(); | ||||
| const { clearUser } = useUserUpdate(); | |||||
| const signOutHandler = async () => { | const signOutHandler = async () => { | ||||
| const data = await signOut({ redirect: false, callbackUrl: '/' }); | const data = await signOut({ redirect: false, callbackUrl: '/' }); | ||||
| clearUser(); | |||||
| router.push(data.url); | router.push(data.url); | ||||
| }; | }; | ||||
| import { Grid, Typography } from '@mui/material'; | import { Grid, Typography } from '@mui/material'; | ||||
| import { Box } from '@mui/system'; | import { Box } from '@mui/system'; | ||||
| import { signOut, useSession } from 'next-auth/react'; | |||||
| import { useSession } from 'next-auth/react'; | |||||
| import { useState } from 'react'; | import { useState } from 'react'; | ||||
| import { updateUser } from '../../requests/user/userUpdateRequest'; | import { updateUser } from '../../requests/user/userUpdateRequest'; | ||||
| import { useUserUpdate } from '../../store/user-context'; | |||||
| import OrderCard from '../cards/order-card/OrderCard'; | import OrderCard from '../cards/order-card/OrderCard'; | ||||
| import ShippingDetailsForm from '../forms/shipping-details/ShippingDetailsForm'; | import ShippingDetailsForm from '../forms/shipping-details/ShippingDetailsForm'; | ||||
| const ProfileContent = ({ orders }) => { | const ProfileContent = ({ orders }) => { | ||||
| const { data: session } = useSession(); | const { data: session } = useSession(); | ||||
| const { updateUserInfo } = useUserUpdate(); | |||||
| const [enableBtn, setEnableBtn] = useState(true); | const [enableBtn, setEnableBtn] = useState(true); | ||||
| const updateUserHandler = async (values) => { | const updateUserHandler = async (values) => { | ||||
| try { | try { | ||||
| setEnableBtn(false); | setEnableBtn(false); | ||||
| updateUserInfo(values); | |||||
| await updateUser(values, session.user._id); | await updateUser(values, session.user._id); | ||||
| signOut(); | |||||
| } catch (error) { | } catch (error) { | ||||
| console.log(error); | console.log(error); | ||||
| setTimeout(() => { | setTimeout(() => { |
| import CircularIndeterminate from '../components/loader/route-loader/CircularIndeterminate'; | import CircularIndeterminate from '../components/loader/route-loader/CircularIndeterminate'; | ||||
| import StorageProvider from '../store/cart-context'; | import StorageProvider from '../store/cart-context'; | ||||
| import CheckoutProvider from '../store/checkout-context'; | import CheckoutProvider from '../store/checkout-context'; | ||||
| import UserProvider from '../store/user-context'; | |||||
| import '../styles/globals.css'; | import '../styles/globals.css'; | ||||
| import theme from '../styles/muiTheme'; | import theme from '../styles/muiTheme'; | ||||
| <Hydrate state={pageProps.dehydratedState}> | <Hydrate state={pageProps.dehydratedState}> | ||||
| <SessionProvider session={session}> | <SessionProvider session={session}> | ||||
| <ThemeProvider theme={theme}> | <ThemeProvider theme={theme}> | ||||
| <Providers components={[CheckoutProvider, StorageProvider]}> | |||||
| <Providers | |||||
| components={[CheckoutProvider, StorageProvider, UserProvider]} | |||||
| > | |||||
| <Layout> | <Layout> | ||||
| <Head> | <Head> | ||||
| <title>Coffee Shop</title> | <title>Coffee Shop</title> |
| const Product = require('../../../../models/product'); | |||||
| import dbConnect from '../../../../utils/helpers/dbHelpers'; | |||||
| const Product = require('../../../models/product'); | |||||
| import dbConnect from '../../../utils/helpers/dbHelpers'; | |||||
| async function handler(req, res) { | async function handler(req, res) { | ||||
| const { method } = req; | const { method } = req; | ||||
| const categoryName = req.query.categoryName; | |||||
| await dbConnect(); | await dbConnect(); | ||||
| const pageIndex = req.query.pageIndex; | |||||
| const category = req.query.category === 'All' ? '' : req.query.category; | |||||
| const filterType = req.query.filterType; | |||||
| if (pageIndex < 1) { | |||||
| res.status(422).json({ | |||||
| message: 'Page does not exist ', | |||||
| }); | |||||
| return; | |||||
| } | |||||
| switch (method) { | switch (method) { | ||||
| case 'GET': { | case 'GET': { | ||||
| try { | try { | ||||
| const productsByCategory = await Product.find({ | |||||
| category: categoryName, | |||||
| }); | |||||
| const productCount = await Product.find({ | |||||
| category: { $regex: category }, | |||||
| }).countDocuments(); | |||||
| if (!productsByCategory) { | |||||
| if (productCount === 0) { | |||||
| res.status(200).json({ | res.status(200).json({ | ||||
| message: | |||||
| 'There are currently no products in our database for the selected category.', | |||||
| productsByCategory: [], | |||||
| message: 'There are currently no products in our database.', | |||||
| product: [], | |||||
| productCount: 0, | |||||
| next: null, | |||||
| previous: null, | |||||
| }); | }); | ||||
| break; | |||||
| } | |||||
| if ((pageIndex - 1) * 9 >= productCount) { | |||||
| throw new Error('Page does not exist!'); | |||||
| } | |||||
| const product = await Product.find({ category: { $regex: category } }) | |||||
| .skip((pageIndex - 1) * 9) | |||||
| .limit(9) | |||||
| .sort(filterType === 'asc' ? 'name' : '-name '); | |||||
| if (!product) { | |||||
| throw new Error('There are currently no products in our database.'); | |||||
| } | } | ||||
| const previousUrl = | |||||
| pageIndex > 1 | |||||
| ? `https://localhost:3000/api/product?pageIndex=${ | |||||
| parseInt(pageIndex) - 1 | |||||
| }` | |||||
| : null; | |||||
| const nextUrl = | |||||
| pageIndex * 9 < productCount | |||||
| ? `https://localhost:3000/api/product?pageIndex=${ | |||||
| parseInt(pageIndex) + 1 | |||||
| }` | |||||
| : null; | |||||
| res.status(200).json({ | res.status(200).json({ | ||||
| message: | |||||
| 'All products from our database for the selected category were fetched successfully.', | |||||
| productsByCategory, | |||||
| message: 'All products from our database were fetched successfully.', | |||||
| product, | |||||
| productCount, | |||||
| next: nextUrl, | |||||
| previous: previousUrl, | |||||
| }); | }); | ||||
| } catch (error) { | } catch (error) { | ||||
| res.status(400).json({ message: error.message }); | res.status(400).json({ message: error.message }); | ||||
| } | } | ||||
| break; | break; | ||||
| } | } | ||||
| case 'POST': { | |||||
| try { | |||||
| const product = await Product.create(req.body); | |||||
| res | |||||
| .status(201) | |||||
| .json({ message: 'Your product was created and stored!', product }); | |||||
| } catch (error) { | |||||
| res.status(400).json({ success: false }); | |||||
| } | |||||
| break; | |||||
| } | |||||
| default: | default: | ||||
| res.status(405).json({ message: 'Method not allowed' }); | res.status(405).json({ message: 'Method not allowed' }); | ||||
| break; | break; |
| import { Box } from '@mui/system'; | import { Box } from '@mui/system'; | ||||
| import { useSession } from 'next-auth/react'; | |||||
| import Head from 'next/head'; | import Head from 'next/head'; | ||||
| import { useEffect } from 'react'; | |||||
| import CompanyInfo from '../components/company-info/CompanyInfo'; | import CompanyInfo from '../components/company-info/CompanyInfo'; | ||||
| import Features from '../components/features/Features'; | import Features from '../components/features/Features'; | ||||
| import Hero from '../components/hero/Hero'; | import Hero from '../components/hero/Hero'; | ||||
| import FeaturedProductsList from '../components/products/featured-products-list/FeaturedPorductsList'; | import FeaturedProductsList from '../components/products/featured-products-list/FeaturedPorductsList'; | ||||
| import { getFeaturedProducts } from '../requests/products/featuredProductsRequest'; | import { getFeaturedProducts } from '../requests/products/featuredProductsRequest'; | ||||
| import { useUserUpdate } from '../store/user-context'; | |||||
| import { getStorage } from '../utils/helpers/storage'; | |||||
| const Home = (props) => { | const Home = (props) => { | ||||
| const { data: session } = useSession(); | |||||
| const { addUser } = useUserUpdate(); | |||||
| useEffect(() => { | |||||
| const userData = getStorage('user-data'); | |||||
| console.log(userData); | |||||
| if (session?.user && userData.length === 0) { | |||||
| addUser(session.user); | |||||
| console.log('added'); | |||||
| } | |||||
| }, [session, addUser]); | |||||
| return ( | return ( | ||||
| <> | <> | ||||
| <Box sx={{ width: '100%', height: '100%' }}> | <Box sx={{ width: '100%', height: '100%' }}> | ||||
| <Head> | <Head> | ||||
| <title>NextJS template</title> | |||||
| <title>Coffee Shop</title> | |||||
| <meta name="description" content="Random data with pagination..." /> | <meta name="description" content="Random data with pagination..." /> | ||||
| </Head> | </Head> | ||||
| <Hero /> | <Hero /> |
| import apiEndpoints from '../apiEndpoints'; | |||||
| export const getAllProducts = async (pageIndex) => { | |||||
| export const getAllProducts = async ({ | |||||
| url, | |||||
| category = 'All', | |||||
| filter = 'asc', | |||||
| }) => { | |||||
| const response = await fetch( | const response = await fetch( | ||||
| `http://localhost:3000${apiEndpoints.products}?page=${pageIndex}` | |||||
| `${url}&category=${category}&filterType=${filter}` | |||||
| ); | ); | ||||
| const data = await response.json(); | const data = await response.json(); |
| import { createContext, useContext, useState } from 'react'; | |||||
| import { | |||||
| getStorage, | |||||
| removeStorage, | |||||
| setStorage, | |||||
| } from '../utils/helpers/storage'; | |||||
| const UserContext = createContext({ | |||||
| userStorage: [], | |||||
| }); | |||||
| const UserDispatchContext = createContext({ | |||||
| addUser: (userData) => {}, | |||||
| clearUser: () => {}, | |||||
| updateUserInfo: (newUserData) => {}, | |||||
| }); | |||||
| export const useUserData = () => { | |||||
| return useContext(UserContext); | |||||
| }; | |||||
| export const useUserUpdate = () => { | |||||
| return useContext(UserDispatchContext); | |||||
| }; | |||||
| const useUser = () => { | |||||
| const USER_KEY = 'user-data'; | |||||
| const [userStorage, setUserStorage] = useState(getStorage(USER_KEY)); | |||||
| const addUser = (userData) => { | |||||
| setStorage(USER_KEY, userData); | |||||
| setUserStorage(userData); | |||||
| }; | |||||
| const updateUserInfo = (newUserData) => { | |||||
| setStorage(USER_KEY, newUserData); | |||||
| setUserStorage(newUserData); | |||||
| }; | |||||
| const clearUser = () => { | |||||
| removeStorage(USER_KEY); | |||||
| setUserStorage(null); | |||||
| }; | |||||
| return { | |||||
| userStorage, | |||||
| setUserStorage, | |||||
| addUser, | |||||
| updateUserInfo, | |||||
| clearUser, | |||||
| }; | |||||
| }; | |||||
| const UserProvider = ({ children }) => { | |||||
| const { userStorage, setUserStorage, addUser, updateUserInfo, clearUser } = | |||||
| useUser(); | |||||
| return ( | |||||
| <UserContext.Provider value={{ userStorage }}> | |||||
| <UserDispatchContext.Provider | |||||
| value={{ | |||||
| setUserStorage, | |||||
| addUser, | |||||
| updateUserInfo, | |||||
| clearUser, | |||||
| }} | |||||
| > | |||||
| {children} | |||||
| </UserDispatchContext.Provider> | |||||
| </UserContext.Provider> | |||||
| ); | |||||
| }; | |||||
| export default UserProvider; |