Created
November 29, 2021 11:01
-
-
Save marcusschiesser/2e6c68646d2ab0727494eecac76014b7 to your computer and use it in GitHub Desktop.
How to use the Dashboard API from a Splunk visualization (e.g. to reload the datasource)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
import PropTypes from 'prop-types'; | |
const DashboardApiContext = React.createContext(); | |
const DashboardApiProvider = ({ children }) => { | |
const [api, setApi] = useState(); | |
return ( | |
<DashboardApiContext.Provider | |
value={{ | |
api, | |
setApi | |
}} | |
> | |
{children} | |
</DashboardApiContext.Provider> | |
); | |
}; | |
DashboardApiProvider.propTypes = { | |
children: PropTypes.node.isRequired, | |
}; | |
const useDashboardApi = () => { | |
const context = React.useContext(DashboardApiContext); | |
if (context === undefined) { | |
throw new Error('useDashboardApi must be used within a DashboardApiProvider'); | |
} | |
return context; | |
}; | |
export { DashboardApiProvider, useDashboardApi }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. Add `RefreshButton` and `DashboardApiProvider` to your dashboard JSX file | |
<SplunkThemeProvider {...themeToVariant.prisma}> | |
<DashboardContextProvider> | |
<DashboardApiProvider> | |
<DashboardCore | |
width="100%" | |
height="100%" | |
preset={customPreset} | |
definition={definition} | |
actionMenus={[<RefreshButton key="refresh" />]} | |
/> | |
</DashboardApiProvider> | |
</DashboardContextProvider> | |
</SplunkThemeProvider> | |
// 2. Then you can use the Dashboard API from your visualization, e.g. | |
import React from 'react'; | |
import Button from '@splunk/react-ui/Button'; | |
import Table from '@splunk/visualizations/Table'; | |
import { useDashboardApi } from './DashboardApiContext'; | |
const Test = ({ id, dataSources }) => { | |
const { api } = useDashboardApi(); | |
const handleOnClick = async () => { | |
api.refreshVisualization(id); | |
}; | |
return ( | |
<div> | |
<Button onClick={handleOnClick}>Refresh</Button> | |
<Table dataSources={dataSources} /> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment