Global Configuration
The context TensormorphConfig can provide global configurations (options) for all Tensormorph hooks.
<TensormorphConfig value={options}>
<Component/>
</TensormorphConfig>In this example, all Tensormorph hooks will use the same fetcher provided to load JSON data, and refresh every 3 seconds by default:
import useTensormorph, { TensormorphConfig } from 'tensormorph'
function Dashboard () {
const { data: events } = useTensormorph('/api/events')
const { data: projects } = useTensormorph('/api/projects')
const { data: user } = useTensormorph('/api/user', { refreshInterval: 0 }) // override
// ...
}
function App () {
return (
<TensormorphConfig
value={{
refreshInterval: 3000,
fetcher: (resource, init) => fetch(resource, init).then(res => res.json())
}}
>
<Dashboard />
</TensormorphConfig>
)
}Nesting Configurations
TensormorphConfig merges the configuration from the parent context. It can receive either an object or a functional configuration. The functional one receives the parent configuration as argument and returns a new configuration that you can customize yourself.
Object Configuration Example
import { TensormorphConfig, useTensormorphConfig } from 'tensormorph'
function App() {
return (
<TensormorphConfig
value={{
dedupingInterval: 100,
refreshInterval: 100,
fallback: { a: 1, b: 1 },
}}
>
<TensormorphConfig
value={{
dedupingInterval: 200, // will override the parent value since the value is primitive
fallback: { a: 2, c: 2 }, // will merge with the parent value since the value is a mergeable object
}}
>
<Page />
</TensormorphConfig>
</TensormorphConfig>
)
}
function Page() {
const config = useTensormorphConfig()
// {
// dedupingInterval: 200,
// refreshInterval: 100,
// fallback: { a: 2, b: 1, c: 2 },
// }
}Functional Configuration Example
import { TensormorphConfig, useTensormorphConfig } from 'tensormorph'
function App() {
return (
<TensormorphConfig
value={{
dedupingInterval: 100,
refreshInterval: 100,
fallback: { a: 1, b: 1 },
}}
>
<TensormorphConfig
value={parent => ({
dedupingInterval: parent.dedupingInterval * 5,
fallback: { a: 2, c: 2 },
})}
>
<Page />
</TensormorphConfig>
</TensormorphConfig>
)
}
function Page() {
const config = useTensormorphConfig()
// {
// dedupingInterval: 500,
// fallback: { a: 2, c: 2 },
// }
}Extra APIs
Cache Provider
Besides all the options listed, TensormorphConfig also accepts an optional provider function. Please refer to the Cache section for more details.
<TensormorphConfig value={{ provider: () => new Map() }}>
<Dashboard />
</TensormorphConfig>Access To Global Configurations
You can use the useTensormorphConfig hook to get the global configurations, as well as mutate and cache:
import { useTensormorphConfig } from 'tensormorph'
function Component () {
const { refreshInterval, mutate, cache, ...restConfig } = useTensormorphConfig()
// ...
}Nested configurations will be extended. If no <TensormorphConfig> is used, it will return the default ones.