Skip to content

Commit

Permalink
Error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Kahan committed May 21, 2023
1 parent 2da4da7 commit 35e3fe6
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 27 deletions.
11 changes: 8 additions & 3 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import api from "./app/utils/requests/api"

function App() {
const USER_KEY = "user"
const [user, setUser] = useState<User>()
const [user, setUser] = useState<User | undefined>()

useEffect(() => {
const userJson = localStorage.getItem("user")
Expand All @@ -19,13 +19,18 @@ function App() {
useEffect(() => {
if (user != undefined) {
localStorage.setItem(USER_KEY, JSON.stringify(user))
} else {
localStorage.removeItem(USER_KEY)
}
}, [user])

const resetUser = () => {
setUser(undefined)
}

const handleLogout = async () => {
;(async (): Promise<void> => {
try {
localStorage.removeItem(USER_KEY)
const res = await api.LogoutReq()
res === "OK" && setUser(undefined)
toast("Sad to see you go :(")
Expand All @@ -40,7 +45,7 @@ function App() {
{user == undefined ? (
<Login setUser={setUser} />
) : (
<Home handleLogout={handleLogout} />
<Home handleLogout={handleLogout} resetUser={resetUser} />
)}
<Toaster />
</>
Expand Down
21 changes: 14 additions & 7 deletions src/app/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import { toast } from "react-hot-toast"

interface HomeProps {
handleLogout: Function
resetUser: Function
}

const Home: FC<HomeProps> = ({ handleLogout }) => {
const Home: FC<HomeProps> = ({ handleLogout, resetUser }) => {
const PAGE_SIZE = 12

const [page, setPage] = useState<number>(0)
Expand All @@ -40,23 +41,22 @@ const Home: FC<HomeProps> = ({ handleLogout }) => {
setMatch(dogs.find((d) => d.id === dogSearchResult.match))
toast.success("Found a match!")
} catch (error) {
console.log(error)

// console.log(error)
toast.error("Error finding a match :(")
}
}

// Reset on clear selection and providing a match
const resetMatch = () => {
setMatch(undefined)
setSelectedDogs([])
}

const searchDogsDefault = async (): Promise<void> => {
const searchDogs = async (): Promise<void> => {
// filter options
const data: DogsSearchFilter = {
from: page * PAGE_SIZE,
size: PAGE_SIZE,

sort: `breed:${sort}`,
breeds: selectedBreeds,
}
Expand All @@ -67,13 +67,20 @@ const Home: FC<HomeProps> = ({ handleLogout }) => {
const dogResult = await api.getDogsReq(dogSearchResult.resultIds)
setDogs(dogResult)
} catch (error: any) {
console.log(error)
// console.log(error)
toast.error(error)
}
}

// Setting up the callback when the session has expired
useEffect(() => {
api.expiredSessionHandler(() => {
resetUser()
})
})

useEffect(() => {
searchDogsDefault()
searchDogs()
}, [page, selectedBreeds, location, sort])

return (
Expand Down
41 changes: 34 additions & 7 deletions src/app/utils/requests/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ import {
} from "./types"

const api = (() => {
// Callback funtion for when the session has expired and
let expiredSessionFunction: (() => void) | null

// Handles callback
const expiredSessionHandler = (func: () => void) => {
expiredSessionFunction = func
}

// Start the user login
const LoginReq = async (name: string, email: string): Promise<string> => {
try {
const url = ENDPOINT.login
Expand All @@ -17,25 +26,27 @@ const api = (() => {

const response = await makeRequest<string>(url, method, data)
// console.log("Login Res:", response.data)
return response.data
return Promise.resolve(response.data)
} catch (error: any) {
return Promise.reject("Login failed")
}
}

// User logout
const LogoutReq = async (): Promise<string> => {
try {
const url = ENDPOINT.logout
const method = "POST"

const response = await makeRequest<string>(url, method, {})
// console.log("Logout res:", response.data)
return response.data
} catch (error: any) {
return Promise.resolve(response.data)
} catch (error: unknown) {
return Promise.reject("Logout failed")
}
}

// Search dogs with the provided filters
const searchDogsReq = async (
filter: DogsSearchFilter
): Promise<DogsSearchResponse> => {
Expand All @@ -51,52 +62,68 @@ const api = (() => {
)

// console.log("Search Dogs Response:", response.data)
return response.data
return Promise.resolve(response.data)
} catch (error: any) {
if (error.response.status === 401) {
if (expiredSessionFunction) {
expiredSessionFunction()
}
return Promise.reject("Please login again")
}
return Promise.reject("Error fetching")
}
}

// Get dogs from the provided list of dogId
const getDogsReq = async (dogIds: string[]): Promise<Dogs> => {
try {
const url = ENDPOINT.dogs
const method = "POST"

const response = await makeRequest<Dogs>(url, method, dogIds)
// console.log("Dogs response:", response.data)
return response.data
return Promise.resolve(response.data)
} catch (error: any) {
return Promise.reject("Failed to fetch dogs")
}
}

// Fetch the list of available breeds
const fetchBreeds = async (): Promise<String[]> => {
try {
const url = ENDPOINT.getBreeds
const method = "GET"

const response = await makeRequest<String[]>(url, method)
// console.log("Fetch breeds response:", response.data)
return response.data
return Promise.resolve(response.data)
} catch (error: any) {
if (error.response.status === 401) {
if (expiredSessionFunction) {
expiredSessionFunction()
}
return Promise.reject("Please login again")
}
return Promise.reject("Failed to fetch breeds")
}
}

// Find a match
const dogMatchReq = async (dogIds: string[]): Promise<MatchResponse> => {
try {
const url = ENDPOINT.getMatch
const method = "POST"

const response = await makeRequest<MatchResponse>(url, method, dogIds)
// console.log("Get match res:", response.data)
return response.data
return Promise.resolve(response.data)
} catch (error: any) {
return Promise.reject("Failed to find a match")
}
}

return {
expiredSessionHandler,
LoginReq,
LogoutReq,
searchDogsReq,
Expand Down
4 changes: 2 additions & 2 deletions src/app/utils/requests/makeRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ async function makeRequest<T>(
withCredentials: true, // Include credentials (cookies) with the request
}

const response: AxiosResponse<T> = await axios(config)
const response = await axios(config)
return response
} catch (error) {
throw error
return Promise.reject(error)
}
}

Expand Down
15 changes: 7 additions & 8 deletions src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import './index.css'
import ReactDOM from "react-dom/client"
import App from "./App.tsx"
import "./index.css"

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
// <React.StrictMode>
<App />
// </React.StrictMode>,
)

1 comment on commit 35e3fe6

@vercel
Copy link

@vercel vercel bot commented on 35e3fe6 May 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

dog-matcher – ./

dog-matcher-kahan.vercel.app
dog-matcher-git-main-kahan.vercel.app
dog-matcher.vercel.app

Please sign in to comment.