Skip to content
This repository has been archived by the owner on Jan 3, 2025. It is now read-only.

Commit

Permalink
Save schedule view via new useStoredState hook (#403)
Browse files Browse the repository at this point in the history
* Create useStoredState hook

* Use new stored state hook for calendar active view

* Add clarifying remarks to hook documentation
  • Loading branch information
kr-matthews authored Dec 20, 2023
1 parent 6104ddd commit 6095334
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
30 changes: 30 additions & 0 deletions Frontend/src/hooks/useStoredState.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useState } from 'react'

/**
* This functions like the useState hook, but it fetches the state stored in
* local storage, via the given key, on subsequent uses.
*
* Do NOT call this twice with the same key - updating one of such a pair
* will not update the other's state.
*
* Currently only works for strings, but can be generalized with JSON.parse
* and JSON.stringify if needed.
*/
export function useStoredState(initialState, key) {
const storedState = localStorage.getItem(key)

const [state, setState] = useState(() => {
if (storedState === null) {
localStorage.setItem(key, initialState)
return initialState
}
return storedState
})

function setAndStoreState(newState) {
setState(newState)
localStorage.setItem(key, newState)
}

return [state, setAndStoreState]
}
4 changes: 2 additions & 2 deletions Frontend/src/pages/schedule/Schedule.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useReducer, useState } from 'react'
import { Message, Segment } from 'semantic-ui-react'
import { useStoredState } from '../../hooks/useStoredState'
import { getDatesStartingOn } from '../../lib/dates'
import CalendarView from './CalendarView'
import EventsSelector from './EventsSelector'
Expand Down Expand Up @@ -144,8 +145,7 @@ export default function Schedule({ wcif }) {

// view

// TODO: save in local storage via a new `useSavedState` hook
const [activeView, setActiveView] = useState('calendar')
const [activeView, setActiveView] = useStoredState('calendar', 'scheduleView')

// TODO: if time zones are changeable, these may be wrong
const activeDates = getDatesStartingOn(
Expand Down

0 comments on commit 6095334

Please sign in to comment.