Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(swagger-ui-react): re-render on spec property change #9966

Merged
merged 1 commit into from
May 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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