Hello, I want to fetch data from the REST API in the onSearch function, but I’m getting a ‘window is not defined’ error. How can I solve this issue? My Node version is 18.14.2, and my npm version is 9.5.0.
/** @jsx jsx */
import { jsx } from '@emotion/core';
import { useCallback } from 'react';
import { JQLEditorAsync as JQLEditor } from '@atlassianlabs/jql-editor';
import { useAutocompleteProvider } from '@atlassianlabs/jql-editor-autocomplete-rest';
import Button from '@atlaskit/button';
const getInitialData = async (url) => {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ includeCollapsedFields: true })
});
const data = response.json();
return {
jqlFields: data.visibleFieldNames,
jqlFunctions: data.visibleFunctionNames,
};
};
const getSuggestions = async (url) => {
const response = await fetch(url);
return response.json();
};
const MyJQLEditor = ({ jql, setJql }) => {
const EditorCSS = {
editor: {
display: 'flex',
flexDirection: 'row',
alignItems: 'start',
marginTop: '50px',
height: '20px',
},
button: {
marginLeft: '10px',
height: '35px'
}
}
const autocompleteProvider = useAutocompleteProvider('account-operations-{{environment}}', getInitialData, getSuggestions);
const onSearch = useCallback((jql, jast) => {
if (jast.errors.length === 0) {
setJql(jql);
}
window.AP.request({
url: '/rest/api/3/search',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ jql: jql }),
success: function (response) {
console.log(response);
},
error: function (response) {
console.error(response);
}})
}, [setJql]);
return (
<div style={EditorCSS.editor}>
<JQLEditor
analyticsSource={'account-operations-{{environment}}'}
query={''}
onSearch={onSearch}
autocompleteProvider={autocompleteProvider}
locale={"en"}
/>
<Button style={EditorCSS.button}>Save the query as a filter</Button>
</div>
);
};
export default MyJQLEditor;