Skip to content

Commit

Permalink
🔒 (react) Update iframe src after deleting session param
Browse files Browse the repository at this point in the history
Closes #8
  • Loading branch information
laymonage committed Nov 14, 2021
1 parent 1ebdf2a commit 51fbb5b
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions packages/react/lib/Giscus.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'
import React, { useEffect, useRef, useState } from 'react'
import { GiscusProps } from '@shared/types'
import {
addDefaultStyles,
Expand All @@ -16,19 +16,24 @@ function GiscusClient(props: GiscusProps) {
const savedSession = localStorage.getItem(GISCUS_SESSION_KEY)

const [session, setSession] = useState(url.searchParams.get('giscus') || '')
const [src, setSrc] = useState(getIframeSrc({ ...props, session }))
const ref = useRef<HTMLIFrameElement>(null)

useEffect(() => {
if (session) {
localStorage.setItem(GISCUS_SESSION_KEY, JSON.stringify(session))
url.searchParams.delete('giscus')
history.replaceState(undefined, document.title, url.toString())
const newOrigin = url.toString()
const newSrc = getIframeSrc({ ...props, session, origin: newOrigin })
setSrc(newSrc)
history.replaceState(undefined, document.title, newOrigin)
return
}

if (savedSession) {
try {
setSession(JSON.parse(savedSession || '') || '')
} catch (e) {
} catch (e: any) {
setSession('')
localStorage.removeItem(GISCUS_SESSION_KEY)
console.warn(`${formatError(e?.message)} Session has been cleared.`)
Expand All @@ -44,14 +49,18 @@ function GiscusClient(props: GiscusProps) {
return () => window.removeEventListener('message', listener)
}, [])

const src = getIframeSrc({ ...props, session })
useEffect(() => {
if (!ref.current) return
ref.current.src = src
}, [src])

return (
<div className="giscus">
<IframeResizer
className="giscus-frame"
title="Comments"
src={src}
forwardRef={ref}
checkOrigin={[GISCUS_ORIGIN]}
/>
</div>
Expand Down

0 comments on commit 51fbb5b

Please sign in to comment.