Skip to content

Commit

Permalink
fix(widget): don't reset palette state while navigating (#4239)
Browse files Browse the repository at this point in the history
  • Loading branch information
shoom3301 authored Apr 15, 2024
1 parent d196b7d commit b963bc3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo } from 'react'
import { useEffect, useState } from 'react'

import { CowSwapWidgetPaletteParams } from '@cowprotocol/widget-lib'

Expand All @@ -7,17 +7,27 @@ import { useLocation } from 'react-router-dom'
// The theme palette provided by a consumer
export function useInjectedWidgetPalette(): Partial<CowSwapWidgetPaletteParams> | undefined {
const { search } = useLocation()
const [paletteParams, setPaletteParams] = useState<CowSwapWidgetPaletteParams | undefined>(undefined)

return useMemo(() => {
useEffect(() => {
const searchParams = new URLSearchParams(search)
const palette = searchParams.get('palette')

// When the palette is not provided, then do nothing
if (!palette) return undefined

// Reset palette state when the value is null
if (palette === 'null') {
setPaletteParams(undefined)
return
}

try {
return JSON.parse(decodeURIComponent(palette))
setPaletteParams(JSON.parse(decodeURIComponent(palette)))
} catch (e) {
console.error('Failed to parse palette from URL', e)
}
}, [search])

return paletteParams
}
6 changes: 5 additions & 1 deletion libs/widget-lib/src/urlUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,16 @@ function addTradeAmountsToQuery(query: URLSearchParams, params: Partial<CowSwapW
function addThemePaletteToQuery(query: URLSearchParams, params: Partial<CowSwapWidgetParams>): URLSearchParams {
const theme = params.theme

if (!theme) return query
if (!theme) {
query.append('palette', 'null')
return query
}

if (isCowSwapWidgetPalette(theme)) {
query.append('palette', encodeURIComponent(JSON.stringify(theme)))
query.append('theme', theme.baseTheme)
} else {
query.append('palette', 'null')
query.append('theme', theme)
}

Expand Down

0 comments on commit b963bc3

Please sign in to comment.