Skip to content
Draft
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
192 changes: 116 additions & 76 deletions pages/events.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { DownOutlined } from '@ant-design/icons'
import type { MenuProps } from 'antd'
import { Button, Dropdown, Space } from 'antd'
import styled from 'styled-components'
import { dummyData } from '@/texts/common/dummy'
import { Event, dummyData } from '@/texts/common/dummy'
import PageNavBar from '@/components/PageNavBar'
import NavBar from '@/components/NavBar'

Expand Down Expand Up @@ -156,9 +156,9 @@ const defaultEventContext: EventContextInterface = {

const EventContext = createContext<EventContextInterface>(defaultEventContext)


const EventSearch = () => {
const { searchString, setSearchString, sortType, sortEvents, query, setQuery } = useContext(EventContext)
const { searchString, setSearchString, sortType, sortEvents, query, setQuery } =
useContext(EventContext)
return (
<SearchBarWrapper>
<SearchBar
Expand All @@ -167,25 +167,31 @@ const EventSearch = () => {
setSearchString(e.target.value)
}}
/>
<Button type="primary" title="Search" onClick={() => {
<Button
type="primary"
title="Search"
onClick={() => {
setQuery(searchString.trim())
}} >
Search
</Button>
}}
>
Search
</Button>
</SearchBarWrapper>
)
}

export default function Events() {
const defaultList = dummyData
export default function Events(data: Event[]) {
const defaultList = data
const [eventsArr, setEventsArr] = useState(defaultList)
const [sortType, setSortType] = useState('0')
const [search, setSearch] = useState('')
const [isNextVisible, setIsNextVisible] = useState(false)
const [isPrevVisible, setIsPrevVisible] = useState(false)
const [pageCount, setPageCount] = useState(1)
const [query, setQuery] = useState("")
const [eventsDisplayed, setEventsDisplayed] = useState(defaultList.length <= 10 ? defaultList : defaultList.slice(0, 9))
const [query, setQuery] = useState('')
const [eventsDisplayed, setEventsDisplayed] = useState(
defaultList.length <= 10 ? defaultList : defaultList.slice(0, 9),
)
const [eventCount, setEventCount] = useState(defaultList.length)

const onClick: MenuProps['onClick'] = ({ key }) => {
Expand All @@ -198,7 +204,7 @@ export default function Events() {
setPageCount(1)
eventCount < 10 && setIsNextVisible(false)
eventCount >= 10 && setIsNextVisible(true)
}
}

const sortEvents = (key) => {
const sortProperty = types[key]
Expand Down Expand Up @@ -230,7 +236,7 @@ export default function Events() {
setEventsArr(sorted)
showFirstPage()
}

const navigateToNext = () => {
setPageCount(pageCount + 1)
setIsPrevVisible(true)
Expand All @@ -243,53 +249,57 @@ export default function Events() {
}

// First useEffect: Update eventCount when the query changes
useEffect(() => {
console.log("Query changed!")
console.log("Query: " + query)
useEffect(() => {
console.log('Query changed!')
console.log('Query: ' + query)

async function fetchQueriedData() {
// Check if the query is blank or empty
if (query.trim() === '') {
setEventCount(defaultList.length)
setPageCount(1)
} else {
Comment on lines +258 to +261

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

try writing code in an "early return" idea.
consider this with multiple cases, will be very clear.

if (case A || case B) { ... return }
if (case C) {... return}
if (case D) {... return}

compared to

if (A) { ...} 
else if (B) {...}
else if (C) {...} 

try {
const realQuery = query.toLowerCase()
const res = await fetch(`https://.../events/${realQuery}`)
const data = await res.json()
const filteredEvents: Event[] = data as Event[]

setEventCount(filteredEvents.length)
setEventsArr(filteredEvents)
} catch (error) {
console.error('Error fetching events data', error)
}
}
}
fetchQueriedData()
}, [query, defaultList])

// Check if the query is blank or empty
if (query.trim() === "") {
setEventCount(defaultList.length)
setPageCount(1)
} else {
// Second useEffect: Update eventsArr based on the filtered query
useEffect(() => {
console.log('Events Array Refreshed!')
const realQuery = query.toLowerCase()
const filtered = defaultList.filter((event) => {
return searchedCategories.some((type) => {
return event[type].toLowerCase().includes(realQuery)
})
})
Comment on lines 281 to 286

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

not truly understanding the use case here, but can try useMemo to return filtered as a value instead.

though after the latest react update we might no longer need all these KEK

setEventCount(filtered.length)
setEventsArr(filtered)
}
}, [query, defaultList]);

// Second useEffect: Update eventsArr based on the filtered query
useEffect(() => {
console.log("Events Array Refreshed!")
const realQuery = query.toLowerCase()
const filtered = defaultList.filter((event) => {
return searchedCategories.some((type) => {
return event[type].toLowerCase().includes(realQuery)
})
})
setEventsArr(filtered)
}, [query, defaultList])

// Third useEffect: Update eventsDisplayed and isNextVisible based on eventCount and pageCount
useEffect(() => {
console.log("Page Count Changed!")
console.log("Page: " + pageCount)
console.log("EventCount: " + eventCount)
}, [query, defaultList])

const startIndex = (pageCount - 1) * 10
const endIndex = Math.min(pageCount * 10, eventCount)
setEventsDisplayed(eventsArr.slice(startIndex, endIndex))
// Third useEffect: Update eventsDisplayed and isNextVisible based on eventCount and pageCount
useEffect(() => {
console.log('Page Count Changed!')
console.log('Page: ' + pageCount)
console.log('EventCount: ' + eventCount)

pageCount === 1 ? setIsPrevVisible(false) : setIsPrevVisible(true)
eventCount < pageCount * 10 ? setIsNextVisible(false) : setIsNextVisible(true)
}, [pageCount, eventCount, eventsArr]);
const startIndex = (pageCount - 1) * 10
const endIndex = Math.min(pageCount * 10, eventCount)
setEventsDisplayed(eventsArr.slice(startIndex, endIndex))


pageCount === 1 ? setIsPrevVisible(false) : setIsPrevVisible(true)
eventCount < pageCount * 10 ? setIsNextVisible(false) : setIsNextVisible(true)
}, [pageCount, eventCount, eventsArr])

return (
<EventContext.Provider
Expand All @@ -300,36 +310,66 @@ useEffect(() => {
setSearchString: setSearch,
sortEvents: sortEvents,
query: query,
setQuery: setQuery
setQuery: setQuery,
}}
>
<NavBar />
<InformationMainContainer>
<Title>UPCOMING EVENTS</Title>
<HeaderWrapper>
<EventSearch />
<Dropdown menu={{ selectable: true, defaultSelectedKeys: ['0'], items, onClick }}>
<a onClick={(e) => e.preventDefault()}>
<Space>
Sort by
<DownOutlined />
</Space>
</a>
</Dropdown>
<EventsAvailable>{eventCount} events available, showing events {(pageCount * 10 - 9)} to {Math.min(pageCount * 10, eventCount)}</EventsAvailable>
</HeaderWrapper>
{eventsDisplayed.map((event, index) => (
<PageSectionComponent
key={index}
title={event.name}
description={event.description}
imgPosition={index % 2 === 0 ? 'left' : 'right'}
imageSrc={event.image}
events
/>
))}
</InformationMainContainer>
<PageNavBar navigateToNext={navigateToNext} navigateToPrev={navigateToPrev} isNextVisible={isNextVisible} isPrevVisible={isPrevVisible}/>
<InformationMainContainer>
<Title>UPCOMING EVENTS</Title>
<HeaderWrapper>
<EventSearch />
<Dropdown menu={{ selectable: true, defaultSelectedKeys: ['0'], items, onClick }}>
<a onClick={(e) => e.preventDefault()}>
<Space>
Sort by
<DownOutlined />
</Space>
</a>
</Dropdown>
<EventsAvailable>
{eventCount} events available, showing events {pageCount * 10 - 9} to{' '}
{Math.min(pageCount * 10, eventCount)}
</EventsAvailable>
</HeaderWrapper>
{eventsDisplayed.map((event, index) => (
<PageSectionComponent
key={index}
title={event.name}
description={event.description}
imgPosition={index % 2 === 0 ? 'left' : 'right'}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

notice how === 0 is not required here~

imageSrc={event.image}
events
/>
))}
</InformationMainContainer>
<PageNavBar
navigateToNext={navigateToNext}
navigateToPrev={navigateToPrev}
isNextVisible={isNextVisible}
isPrevVisible={isPrevVisible}
/>
</EventContext.Provider>
)
}

// direct database queries.
export async function getStaticProps() {
try {
const res = await fetch('https://.../events')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

could consider using a promise instead.

const posts = await res.json()
const data: Event[] = posts as Event[]

return {
props: {
data,
},
}
} catch (error) {
console.error('Error fetching events data', error)
return {
props: {
data: [], // Empty array or other default data
},
}
}
}
43 changes: 32 additions & 11 deletions pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import styled from 'styled-components'
import Image from 'next/image'
import Carousel from '@/components/Carousel'

const carouselPhotos = [
{ id: 1, src: '/assets/sample-photos/photo1.jpg' },
{ id: 2, src: '/assets/sample-photos/photo2.jpg' },
{ id: 3, src: '/assets/sample-photos/photo3.jpg' },
{ id: 4, src: '/assets/sample-photos/photo4.jpg' },
{ id: 5, src: '/assets/sample-photos/photo4.jpg' },
{ id: 6, src: '/assets/sample-photos/photo3.jpg' },
{ id: 7, src: '/assets/sample-photos/photo2.jpg' },
{ id: 8, src: '/assets/sample-photos/photo1.jpg' },
]
// const carouselPhotos = [
// { id: 1, src: '/assets/sample-photos/photo1.jpg' },
// { id: 2, src: '/assets/sample-photos/photo2.jpg' },
// { id: 3, src: '/assets/sample-photos/photo3.jpg' },
// { id: 4, src: '/assets/sample-photos/photo4.jpg' },
// { id: 5, src: '/assets/sample-photos/photo4.jpg' },
// { id: 6, src: '/assets/sample-photos/photo3.jpg' },
// { id: 7, src: '/assets/sample-photos/photo2.jpg' },
// { id: 8, src: '/assets/sample-photos/photo1.jpg' },
// ]

const HomeContainer = styled.div`
display: flex;
Expand All @@ -36,7 +36,7 @@ const CaptionContainer = styled.div`
text-align: center;
`

export default function Home() {
export default function Home(carouselPhotos) {
console.log(typeof carouselPhotos)
return (
<HomeContainer>
Expand All @@ -51,3 +51,24 @@ export default function Home() {
</HomeContainer>
)
}

export async function getStaticProps() {
try {
// Fetch photo URLs from the API route
const response = await fetch('/api/carouselPhotos') // This is the URL of your API route
const carouselPhotos = await response.json()

return {
props: {
carouselPhotos,
},
}
} catch (error) {
console.error('Error fetching photos', error)
return {
props: {
carouselPhotos: [],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

not very elegant but can handle errors by adding new props
carouselPhotos: {
data: [],
error: {
message: "unauthorised query"
status: 401
}
}

},
}
}
}