Fetch a config.json
Fetch a config.json at runtime, then build the view state.
If the config lives on a server โ or differs per environment, per user, or per
route โ fetch it before constructing createViewState. Wrap viewState in
useState/useEffect so React renders once the fetch resolves:
function App() {
const [state, setState] = useState()
useEffect(() => {
;(async () => {
const config = await (await fetch('/config.json')).json()
setState(createViewState({ config }))
})()
}, [])
return state ? <JBrowseApp viewState={state} /> : null
}
As with a bundled config, URIs in the file are
resolved relative to where it was downloaded from, so tag each location with a
baseUri after fetching. The config shape is documented in
JBrowseRootConfig.
Live demo
View source
import { useEffect, useState } from 'react'
import { JBrowseApp, createViewState } from '@jbrowse/react-app2'
import { addRelativeUris } from '../volvoxConfig.ts'
type ViewState = ReturnType<typeof createViewState>
// The config's URIs are relative to where it lives. addRelativeUris tags each
// with a baseUri so JBrowse resolves them against that directory at load time.
const configUrl =
'https://jbrowse.org/code/jb2/main/test_data/volvox/config.json'
export default function WithFetchConfigJson() {
const [state, setState] = useState<ViewState>()
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
;(async () => {
const response = await fetch(configUrl)
if (!response.ok) {
throw new Error(`HTTP ${response.status} fetching config ${configUrl}`)
}
const config = await response.json()
addRelativeUris(config, configUrl)
setState(createViewState({ config }))
})()
}, [])
return state ? <JBrowseApp viewState={state} /> : null
}