Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zustand implementation and useCookie hook #47

Merged
merged 2 commits into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@
"storybook-addon-apollo-client": "^5.0.0",
"swiper": "^11.0.7",
"tailwindcss": "3.3.3",
"ts-node": "^10.9.2"
"ts-node": "^10.9.2",
"zustand": "^4.5.2"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
Expand Down
16 changes: 0 additions & 16 deletions src/__tests__/home.test.tsx

This file was deleted.

65 changes: 0 additions & 65 deletions src/__tests__/query.test.tsx

This file was deleted.

35 changes: 0 additions & 35 deletions src/__tests__/searchBar.test.tsx

This file was deleted.

3 changes: 3 additions & 0 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ import { motion } from 'framer-motion'
import StarIcon from '../assets/stars.svg'
import Image from 'next/image'
import DiscordIcon from '@assets/discord.svg'
import useCookie from '@/hooks/useCookie'
export default function Home() {
const [searchOpen, setSearchOpen] = useState(false)

const LANDING_PAGE_TEXT = ' Search universities worldwide and become part of their online communities'.split(' ')
const [cookieValue] = useCookie('uni_user_token')
console.log(cookieValue)

return (
<div className="home">
Expand Down
23 changes: 23 additions & 0 deletions src/hooks/useCookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useState, useEffect } from 'react'

const useCookie = (cookieName: string): [string, (value: string, expirationDate: string) => void, () => void] => {
const [cookieValue, setCookieValue] = useState<string>('')

useEffect(() => {
const cookie = document.cookie.split('; ').find((row) => row.startsWith(`${cookieName}=`))

setCookieValue(cookie ? cookie.split('=')[1] : '')
}, [cookieName])

const setCookie = (value: string, expirationDate: string): void => {
document.cookie = `${cookieName}=${value}; expires=${new Date(expirationDate).toUTCString()}; path=/`
}

const deleteCookie = (): void => {
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
}

return [cookieValue, setCookie, deleteCookie]
}

export default useCookie
11 changes: 11 additions & 0 deletions src/models/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ export interface UserResponseType {
tokens: Tokens
}

interface verifiedInterface {
communityId: string
communityName: string
}
interface unverifiedInterface {
communityId: string
communityName: string
}

export interface User {
firstName: string
lastName: string
Expand All @@ -17,6 +26,8 @@ export interface User {
role: string
isEmailVerified: boolean
id: string
userVerifiedCommunities: verifiedInterface[]
userUnVerifiedCommunities: unverifiedInterface[]
}

export interface Tokens {
Expand Down
18 changes: 16 additions & 2 deletions src/services/auth.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,30 @@
import { LoginForm, UserResponseType } from '@/models/auth'
import { useMutation } from '@tanstack/react-query'
import { client } from './api-Client'
import { useUniStore } from '@/store/store'
import useCookie from '@/hooks/useCookie'

const login = async (data: LoginForm): Promise<UserResponseType> => {
const result = await client<UserResponseType, LoginForm>('auth/login', { data })
return result
}

export const useHandleLogin = () =>
useMutation({
export const useHandleLogin = () => {
const setUserData = useUniStore((state) => state.setUserData)
// const setToken = useUniStore((state) => state.setToken)
const [_, setCookieValue] = useCookie('uni_user_token')
const [__, setRefreshCookieValue] = useCookie('uni_user_refresh_token')

return useMutation({
mutationFn: (data: LoginForm) => login(data),
onSuccess: (response) => {
console.log(response, 'response')
console.log(_, __)

setUserData(response.user)
// setToken(response.tokens)
setCookieValue(response.tokens.access.token, response.tokens.access.expires)
setRefreshCookieValue(response.tokens.refresh.token, response.tokens.refresh.expires)
},
})
}
19 changes: 19 additions & 0 deletions src/store/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import { createUserSlice } from './userSlice/userSlice'
import { storeType } from './storeType'

export const useUniStore = create<storeType>()(
devtools(
persist(
(...a) => ({
...createUserSlice(...a),
}),
{
name: 'UniStore',
// partialize: (state) => ({ products: state.products,userName:state.userName }),
// skipHydration: true
}
)
)
)
3 changes: 3 additions & 0 deletions src/store/storeType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { userSlice } from './userSlice/userSlice'

export type storeType = userSlice
35 changes: 35 additions & 0 deletions src/store/userSlice/userSlice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { StateCreator } from 'zustand'
import { userType } from './userType'

type userState = {
userData: userType
}

type userAction = {
setUserData: (userData: userType) => void
resetUserData: () => void
}

const initialState: userState = {
userData: {
firstName: '',
lastName: '',
email: '',
// password: '',
gender: '',
dob: '',
role: '',
isEmailVerified: false,
// createdAt: '',
userVerifiedCommunities: [],
userUnVerifiedCommunities: [],
},
}

export type userSlice = userState & userAction

export const createUserSlice: StateCreator<userSlice> = (set) => ({
userData: initialState.userData,
setUserData: (userData: userType) => set({ userData }),
resetUserData: () => set(initialState),
})
22 changes: 22 additions & 0 deletions src/store/userSlice/userType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
interface verifiedInterface {
communityId: string
communityName: string
}
interface unverifiedInterface {
communityId: string
communityName: string
}

export interface userType {
firstName: string
lastName: string
email: string
// password: string
gender: string
dob: string
role: string
isEmailVerified: boolean
// createdAt: Date | string
userVerifiedCommunities: verifiedInterface[]
userUnVerifiedCommunities: unverifiedInterface[]
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"jest.config.ts",
"jest.setup.js",
"src/app/components/Slider/Slider.js"
],
, "src/store/userSlice" ],
"exclude": [
"node_modules"
]
Expand Down
Loading