Skip to content

Commit

Permalink
🐛 (react) Fix session param handling
Browse files Browse the repository at this point in the history
  • Loading branch information
laymonage committed Feb 3, 2022
1 parent a10b903 commit 991b842
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions packages/react/lib/Giscus.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from 'react'
import React, { useEffect, useState } from 'react'
import { GiscusProps } from '@shared/types'
import {
addDefaultStyles,
Expand All @@ -11,22 +11,20 @@ import {
import IframeResizer from 'iframe-resizer-react'

function GiscusClient(props: GiscusProps) {
const origin = location.href
const url = new URL(origin)
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)
const [session, setSession] = useState('')
const src = getIframeSrc({ ...props, session })

useEffect(() => {
if (session) {
localStorage.setItem(GISCUS_SESSION_KEY, JSON.stringify(session))
const origin = location.href
const url = new URL(origin)
const savedSession = localStorage.getItem(GISCUS_SESSION_KEY)
const urlSession = url.searchParams.get('giscus') || ''

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

Expand All @@ -50,8 +48,10 @@ function GiscusClient(props: GiscusProps) {
}, [])

useEffect(() => {
if (!ref.current) return
ref.current.src = src
const iframes = document.getElementsByClassName('giscus-frame')
if (!iframes.length) return
const iframe = iframes[0] as HTMLIFrameElement
iframe.src = src
}, [src])

return (
Expand All @@ -60,7 +60,6 @@ function GiscusClient(props: GiscusProps) {
className="giscus-frame"
title="Comments"
src={src}
forwardRef={ref}
checkOrigin={[GISCUS_ORIGIN]}
/>
</div>
Expand Down

0 comments on commit 991b842

Please sign in to comment.