Skip to content

Commit

Permalink
Remove manual fetch from storeprovider and memoise values for better …
Browse files Browse the repository at this point in the history
…perf
  • Loading branch information
DinerIsmail committed Nov 8, 2023
1 parent 3ed411a commit 7fe3415
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 32 deletions.
2 changes: 0 additions & 2 deletions components/admin/nav/web-selector/WebSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ const WebSelector = () => {
const { permissions } = usePermissions()
const { ownerships } = useMyOwnerships()

console.log({ webs, ownerships })

const allUniqueWebIds = useMemo(() => {
if (!permissions && !ownerships) {
return []
Expand Down
52 changes: 22 additions & 30 deletions store/StoreProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useEffect, useState, useMemo } from 'react'
import useLocalStorage from 'use-local-storage'
import { useMediaQuerySSR } from '@hooks/application'
import { AppContext } from '@store/AppContext'
import { useWebs } from '@hooks/webs'

const DEFAULT_SELECTED_WEB = 'cambridge-city'

Expand All @@ -12,9 +13,10 @@ const StoreProvider = ({ children }) => {
'selected-web',
DEFAULT_SELECTED_WEB,
)
const [webs, setWebs] = useState([])
const [subdomain, setSubdomain] = useState<string>()

const { webs } = useWebs()

useEffect(() => {
const hostname = window.location.hostname
if (!hostname.includes('.')) {
Expand All @@ -29,22 +31,6 @@ const StoreProvider = ({ children }) => {
setIsAdminMode(isAdminMode)
}, [])

async function fetchWebs() {
const response = await fetch('/api/webs')

if (response.status === 200) {
const data = await response.json()
const { webs } = data
setWebs(webs)
} else {
console.error('Failed to fetch webs in StoreProvider')
}
}

useEffect(() => {
void fetchWebs()
}, [])

useEffect(() => {
if (subdomain && subdomain !== 'resilienceweb') {
setSelectedWebSlug(subdomain)
Expand All @@ -57,20 +43,26 @@ const StoreProvider = ({ children }) => {
}
}, [selectedWebSlug, webs])

return (
<AppContext.Provider
value={{
isAdminMode,
isMobile,
selectedWebSlug,
setSelectedWebSlug,
selectedWebId,
webs,
}}
>
{children}
</AppContext.Provider>
const value = useMemo(
() => ({
isAdminMode,
isMobile,
selectedWebSlug,
setSelectedWebSlug,
selectedWebId,
webs,
}),
[
isAdminMode,
isMobile,
selectedWebId,
selectedWebSlug,
setSelectedWebSlug,
webs,
],
)

return <AppContext.Provider value={value}>{children}</AppContext.Provider>
}

export default StoreProvider

1 comment on commit 7fe3415

@vercel
Copy link

@vercel vercel bot commented on 7fe3415 Nov 8, 2023

Choose a reason for hiding this comment

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

Please sign in to comment.