Skip to content

Commit

Permalink
fix(swagger-ui-react): re-render on spec prop change (#9966)
Browse files Browse the repository at this point in the history
Refs #9965
  • Loading branch information
glowcloud authored May 27, 2024
1 parent e57d0be commit df03a8f
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions flavors/swagger-ui-react/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,20 @@
*/
"use client"

import React, { useEffect, useState } from "react"
import React, { useEffect, useRef, useState } from "react"
import PropTypes from "prop-types"
import SwaggerUIConstructor from "#swagger-ui"

const { config } = SwaggerUIConstructor

const usePrevious = (value) => {
const ref = useRef()
useEffect(() => {
ref.current = value
}, [value])
return ref.current
}

const SwaggerUI = ({
spec = config.defaults.spec,
url = config.defaults.url,
Expand Down Expand Up @@ -40,6 +48,8 @@ const SwaggerUI = ({
}) => {
const [system, setSystem] = useState(null)
const SwaggerUIComponent = system?.getComponent("App", "root")
const prevSpec = usePrevious(spec)
const prevUrl = usePrevious(url)

useEffect(() => {
const systemInstance = SwaggerUIConstructor({
Expand Down Expand Up @@ -84,22 +94,30 @@ const SwaggerUI = ({
useEffect(() => {
if (system) {
const prevStateUrl = system.specSelectors.url()
if (url !== prevStateUrl) {
if (url !== prevStateUrl || url !== prevUrl) {
system.specActions.updateSpec("")
if (url) {
system.specActions.updateUrl(url)
system.specActions.download(url)
}
}
}
}, [system, url])

useEffect(() => {
if (system) {
const prevStateSpec = system.specSelectors.specStr()
if (spec && spec !== prevStateSpec) {
if (
spec &&
spec !== SwaggerUIConstructor.config.defaults.spec &&
(spec !== prevStateSpec || spec !== prevSpec)
) {
const updatedSpec =
typeof spec === "object" ? JSON.stringify(spec) : spec
system.specActions.updateSpec(updatedSpec)
}
}
}, [system, url, spec])
}, [system, spec])

return SwaggerUIComponent ? <SwaggerUIComponent /> : null
}
Expand Down

0 comments on commit df03a8f

Please sign in to comment.