Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Handle incorrect types in cookie value (#798)

Dhruv Bhanushali9da028e6f580
diff --git a/frontend/src/stores/ui.ts b/frontend/src/stores/ui.ts
index dca73e3ed..796464674 100644
--- a/frontend/src/stores/ui.ts
+++ b/frontend/src/stores/ui.ts
@@ -133,16 +133,38 @@ export const useUiStore = defineStore("ui", {
* Given a list of key value pairs of UI state parameters and their states,
* populate the store state to match the cookie.
*
+ * Since the cookies are passed through `JSON.parse()`, they can have the
+ * wrong types. This function resets cookies to the default value if their
+ * type is incorrect.
+ *
* @param cookies - mapping of UI state parameters and their states.
*/
initFromCookies(cookies: OpenverseCookieState) {
- this.updateBreakpoint(cookies.uiBreakpoint ?? this.breakpoint)
- this.isFilterDismissed = cookies.uiIsFilterDismissed ?? false
- this.isMobileUa = cookies.uiIsMobileUa ?? false
+ let breakpoint = this.breakpoint
+ if (
+ cookies.uiBreakpoint &&
+ Object.keys(ALL_SCREEN_SIZES).includes(cookies.uiBreakpoint)
+ )
+ breakpoint = cookies.uiBreakpoint
+ this.updateBreakpoint(breakpoint)
+
+ if (typeof cookies.uiIsFilterDismissed === "boolean") {
+ this.isFilterDismissed = cookies.uiIsFilterDismissed
+ }
+
+ this.isMobileUa = false
+ if (typeof cookies.uiIsMobileUa === "boolean") {
+ this.isMobileUa = cookies.uiIsMobileUa
+ }
+
this.innerFilterVisible = this.isDesktopLayout
? !this.isFilterDismissed
: false
- this.dismissedBanners = cookies.uiDismissedBanners ?? []
+
+ if (Array.isArray(cookies.uiDismissedBanners)) {
+ this.dismissedBanners = cookies.uiDismissedBanners
+ }
+
this.updateCookies()
},