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

minimize requests to backend from frontend on event page DOT-262 #696

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
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
80 changes: 70 additions & 10 deletions src/events/components/DetailView/index.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,95 @@
import React from 'react';
import Head from 'next/head';
import React, { useEffect } from 'react';
import { useEffect } from 'react';

import Spinner from 'common/components/Spinner';
import { DOMAIN } from 'common/constants/endpoints';
import HttpError from 'core/components/errors/HttpError';
import { useDispatch, useSelector } from 'core/redux/hooks';
import { fetchAttendanceEventById } from 'events/slices/attendanceEvents';
import { eventSelectors, fetchEventById } from 'events/slices/events';
import { fetchAttendanceEventById, setAttendanceEventFromLocalStorage } from 'events/slices/attendanceEvents';
import { fetchEventById, setEventFromLocalStorage } from 'events/slices/events';

import { IAttendanceEvent, IEvent } from 'events/models/Event';
import Contact from './Contact';
import style from './detail.less';
import InfoBox from './InfoBox';
import PictureCard from './PictureCard';
import Registration from './Registation';
import { selectIsLoggedIn } from 'authentication/selectors/authentication';
import style from './detail.less';

interface IProps {
eventId: number;
}

export const getAttendanceEventLSKey = (eventId: number) => `attendanceevent-${eventId}`;
export const getEventLSKey = (eventId: number) => `event-${eventId}`;

export interface ObjectInLocalStorage<T> {
validTo: number;
data: T;
}

const useFetchEvent = (eventId: number) => {
const dispatch = useDispatch();
// see if event in localStorage
const eventStr = localStorage.getItem(getEventLSKey(eventId));
let event: ObjectInLocalStorage<IEvent> | null = null;

useEffect(() => {
if (!eventStr) {
dispatch(fetchEventById(eventId));
} else {
if (eventStr) {
event = JSON.parse(eventStr) as ObjectInLocalStorage<IEvent>;

if (event.validTo < Date.now()) {
dispatch(fetchEventById(eventId));
return;
}

dispatch(setEventFromLocalStorage(event.data));
}
}
}, [eventId, dispatch]);

return event;
};

const useFetchAttendanceEvent = (eventId: number) => {
const dispatch = useDispatch();
// see if event in localStorage
const eventStr = localStorage.getItem(getAttendanceEventLSKey(eventId));
let event: ObjectInLocalStorage<IAttendanceEvent> | null = null;

useEffect(() => {
if (!eventStr) {
dispatch(fetchAttendanceEventById(eventId));
} else {
if (eventStr) {
event = JSON.parse(eventStr) as ObjectInLocalStorage<IAttendanceEvent>;

if (event.validTo < Date.now()) {
dispatch(fetchAttendanceEventById(eventId));
return;
}

dispatch(setAttendanceEventFromLocalStorage(event.data));
}
}
}, [eventId, dispatch]);
return event;
};

export const DetailView = ({ eventId }: IProps) => {
const dispatch = useDispatch();
const event = useSelector((state) => eventSelectors.selectById(state, eventId));
const event = useSelector((state) => state.events.entities[eventId]);
const isPending = useSelector((state) => state.events.loading === 'pending');
const isLoggedIn = useSelector(selectIsLoggedIn());

useFetchEvent(eventId);
useFetchAttendanceEvent(eventId);

useEffect(() => {
window.scrollTo(0, 0);
dispatch(fetchEventById(eventId));
dispatch(fetchAttendanceEventById(eventId));
}, [eventId, dispatch, isLoggedIn]);
}, [eventId, dispatch]);

if (isPending && !event) {
return <Spinner />;
Expand Down
25 changes: 22 additions & 3 deletions src/events/slices/attendanceEvents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { State } from 'core/redux/Store';

import { getAttendanceEvent } from '../api/events';
import { IAttendanceEvent } from '../models/Event';
import { getAttendanceEventLSKey, ObjectInLocalStorage } from 'events/components/DetailView';

const attendanceEventsAdapter = createEntityAdapter<IAttendanceEvent>({
sortComparer: (attendanceEventA, attendanceEventB) => {
Expand All @@ -14,8 +15,20 @@ const attendanceEventsAdapter = createEntityAdapter<IAttendanceEvent>({
export const attendanceEventSelectors = attendanceEventsAdapter.getSelectors<State>((state) => state.attendanceEvents);

export const fetchAttendanceEventById = createAsyncThunk('attendanceEvents/fetchById', async (eventId: number) => {
const events = await getAttendanceEvent(eventId);
return events;
const event = await getAttendanceEvent(eventId);
// write to local storage
if (event) {
const key = getAttendanceEventLSKey(event.id);

const toStore: ObjectInLocalStorage<IAttendanceEvent> = {
data: event,
// valid for 1 hour
validTo: Date.now() + 60 * 60 * 1000,
};

localStorage.setItem(key, JSON.stringify(toStore));
}
return event;
});

interface IState {
Expand All @@ -33,7 +46,11 @@ const INITIAL_STATE: IState = {
export const attendanceEventsSlice = createSlice({
name: 'events',
initialState: attendanceEventsAdapter.getInitialState(INITIAL_STATE),
reducers: {},
reducers: {
setAttendanceEventFromLocalStorage(state, action) {
attendanceEventsAdapter.upsertOne(state, action.payload);
},
},
extraReducers: (builder) => {
builder.addCase(fetchAttendanceEventById.pending, (state) => {
state.loading = 'pending';
Expand All @@ -50,3 +67,5 @@ export const attendanceEventsSlice = createSlice({
});

export const attendanceEventsReducer = attendanceEventsSlice.reducer;

export const { setAttendanceEventFromLocalStorage } = attendanceEventsSlice.actions;
18 changes: 17 additions & 1 deletion src/events/slices/events.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createAsyncThunk, createEntityAdapter, createSlice, SerializedError, unwrapResult } from '@reduxjs/toolkit';
import { State } from 'core/redux/Store';
import { getEvent, IEventAPIParameters, listEvents } from 'events/api/events';
import { getEventLSKey, ObjectInLocalStorage } from 'events/components/DetailView';
import { EventTypeEnum, IEvent } from 'events/models/Event';
import { DateTime, Interval } from 'luxon';

Expand All @@ -24,6 +25,18 @@ export const fetchEvents = createAsyncThunk('events/fetchMultiple', async (optio
export const fetchEventById = createAsyncThunk('events/fetchById', async (eventId: number) => {
const event = await getEvent(eventId);

// write to local storage
if (event) {
const key = getEventLSKey(event.id);

const toStore: ObjectInLocalStorage<IEvent> = {
data: event,
// valid for 1 hour
validTo: Date.now() + 60 * 60 * 1000,
};

localStorage.setItem(key, JSON.stringify(toStore));
}
return event;
});

Expand Down Expand Up @@ -165,6 +178,9 @@ export const eventsSlice = createSlice({
name: 'events',
initialState: eventsAdapter.getInitialState(INITIAL_STATE),
reducers: {
setEventFromLocalStorage(state, action) {
eventsAdapter.upsertOne(state, action.payload);
},
nextEventPage(state) {
state.search.page++;
},
Expand Down Expand Up @@ -221,6 +237,6 @@ export const eventsSlice = createSlice({
},
});

export const { nextEventPage, resetEventPage } = eventsSlice.actions;
export const { nextEventPage, resetEventPage, setEventFromLocalStorage } = eventsSlice.actions;

export const eventsReducer = eventsSlice.reducer;