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

perf: use tanstack query to cache attribute and useDocument requests #1436

Merged
merged 4 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
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
6 changes: 0 additions & 6 deletions e2e/tests/plugin-form-dimensional_scalar.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ test('Dimensional scalar', async ({ page }) => {
await page.getByTestId('number').getByRole('spinbutton').fill('25')
await page.getByRole('textbox').fill('1 mile')
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await expect(page.getByRole('alert')).not.toBeVisible()
await navigate()
await expect(
Expand Down Expand Up @@ -66,8 +64,6 @@ test('Dimensional scalar', async ({ page }) => {
.getByLabel('label (optional)')
.fill('Should not show as config overrides')
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await expect(page.getByRole('alert')).not.toBeVisible()
await page.getByRole('button', { name: 'waveForm' }).click()
await expect(page.getByText('significantWaveHeight (config)')).toBeVisible()
Expand All @@ -92,8 +88,6 @@ test('Dimensional scalar', async ({ page }) => {
await page.getByLabel('label (optional)').fill('New Maximum')
await page.getByLabel('unit (optional)').fill('€')
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await expect(page.getByRole('alert')).not.toBeVisible()
await page.getByRole('button', { name: 'waveForm' }).click()
await expect(
Expand Down
9 changes: 1 addition & 8 deletions e2e/tests/plugin-form-relative_reference.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ test('Relative reference', async ({ page }) => {
await page.getByRole('button', { name: 'Edit' }).last().click()
await page.getByTestId('form-number-widget-A Number').fill('1')
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await expect(page.getByRole('alert')).not.toBeVisible()
await page.getByRole('button', { name: 'Close data' }).click()

Expand All @@ -37,9 +35,8 @@ test('Relative reference', async ({ page }) => {
await page.getByTestId('form-number-widget-A Number').fill('10')
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await expect(page.getByRole('alert')).not.toBeVisible()
await page.getByRole('button', { name: 'Close job' }).click()
await page.waitForTimeout(5000) // Wait for react-query cache to expire
await page.getByTestId('data').getByText('Data').click()
await expect(page.getByRole('code')).toBeVisible()
await page.getByRole('button', { name: 'Edit' }).last().click()
Expand All @@ -65,8 +62,6 @@ test('Relative reference', async ({ page }) => {
await page.getByTestId('form-number-widget-A Number').fill('2')
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await expect(page.getByRole('alert')).not.toBeVisible()
await page.getByRole('button', { name: 'Close data' }).click()
await page.getByTestId('job').getByText('Job').last().click()
await expect(page.getByRole('code')).toBeVisible()
Expand Down Expand Up @@ -101,8 +96,6 @@ test('Relative reference', async ({ page }) => {
await page.getByTestId('form-number-widget-A Number').fill('3')
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await expect(page.getByRole('alert')).not.toBeVisible()
await page.getByRole('button', { name: 'Close data' }).click()
await page.getByText('Job', { exact: true }).nth(3).click()
await expect(page.getByRole('code')).toBeVisible()
Expand Down
8 changes: 1 addition & 7 deletions e2e/tests/plugin-list-task_list.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ test('task list', async ({ page }) => {
.getByLabel('Task description: (Optional)')
.fill('Review and submit the tax return.')
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await page.getByLabel('Close task_list').click()
await page.getByTestId('task_list').getByLabel('Open in tab').click()
await expect(page.getByText('Tax return', { exact: true })).toBeVisible()
Expand Down Expand Up @@ -53,8 +51,6 @@ test('task list', async ({ page }) => {
).toHaveValue('Wash the car')
await page.getByText('Mark task as complete').first().click()
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await page.getByLabel('Close task_list').click()
await page.getByTestId('task_list').getByLabel('Open in tab').click()
await page
Expand Down Expand Up @@ -223,8 +219,6 @@ test('task list', async ({ page }) => {
.getByLabel('Task description: (Optional)')
.fill('Remember to buy new brush.')
await page.getByRole('button', { name: 'Submit' }).click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()
await page.getByLabel('Close task_list').click()
await page.getByTestId('task_list').getByLabel('Open in tab').click()
await expect(
Expand All @@ -243,7 +237,7 @@ test('task list', async ({ page }) => {
await expect(page.getByLabel('Task description: (Optional)')).toHaveValue(
'Remember to buy new brush.'
)
await page.getByRole('button', { name: 'Minimize item' }).last().click()
await page.getByTestId('expandListItem-2').click()
})

await test.step('Pagination', async () => {
Expand Down
2 changes: 0 additions & 2 deletions e2e/tests/plugin-table-car_list.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ test('Table car list example', async ({ page }) => {
await page.getByLabel('Model').fill('e-tron')
await page.getByLabel('Color (Optional)').fill('Black')
await page.getByTestId('form-submit').click()
await expect(page.getByRole('alert')).toHaveText(['Document updated'])
await page.getByRole('button', { name: 'close', exact: true }).click()

//Currently we need to reload application to view saved values...
await page.reload()
Expand Down
1 change: 1 addition & 0 deletions example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"dependencies": {
"@development-framework/dm-core": "^1.3.3",
"@development-framework/dm-core-plugins": "^1.3.3",
"@tanstack/react-query": "^5.37.1",
"plotly.js": "^2.18.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand Down
3 changes: 3 additions & 0 deletions packages/dm-core-plugins/src/form/FormPlugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ export const FormPlugin = (props: IUIPlugin) => {
props.idReference,
0
)

// react-hook-form is unable to rerender when the document is updated.
// This means that the form will not benefit from react-query caching.
if (isLoading) return <Loading />

if (error) throw new Error(JSON.stringify(error, null, 2))
Expand Down
8 changes: 7 additions & 1 deletion packages/dm-core-plugins/src/form/components/Form.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'

import {
EBlueprint,
Expand Down Expand Up @@ -49,6 +49,12 @@ export const Form = (props: TFormProps) => {
defaultValues: formData || {},
})

useEffect(() => {
if (formData) {
rootMethods.reset(formData, { keepDefaultValues: false })
}
}, [formData])

const childMethods = useFormContext()

const methods = showSubmitButton ? rootMethods : childMethods
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const DimensionalScalarWidget = (props: TWidget) => {
helperText={error}
variant={error ? 'error' : undefined}
onChange={onChangeHandler}
defaultValue={isPrimitive ? entity : entity?.value ?? ''}
value={isPrimitive ? entity : entity?.value ?? ''}
/>
</EdsProvider>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const EntityPickerWidget = (props: TWidget) => {
<TextField
id={props.id}
readOnly={props.readOnly}
defaultValue={props.value}
value={props.value}
inputRef={props.inputRef}
variant={props.variant}
helperText={props.helperText}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const SwitchWidget = (props: TWidget) => {
<Switch
{...props}
disabled={readOnly}
defaultChecked={typeof value === 'undefined' ? false : value}
checked={typeof value === 'undefined' ? false : value}
data-testid='form-switch'
/>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const StyledTextField = (
return (
<StyledEDSField
{...restProps}
defaultValue={
value={
props.readOnly && props.value === ''
? '-'
: props.defaultValue ?? props.value
Expand Down Expand Up @@ -99,7 +99,7 @@ export const StyledNumberField = (
onWheel={(event: React.UIEvent<HTMLInputElement>) =>
(event.target as HTMLInputElement).blur()
}
defaultValue={value ?? props.defaultValue}
value={value ?? props.defaultValue}
type={'number'}
/>
)
Expand Down
6 changes: 5 additions & 1 deletion packages/dm-core/src/ApplicationContext.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import React, {
Dispatch,
ReactNode,
Expand All @@ -20,6 +21,7 @@ const DEFAULT_ROLE: TRole = {
authServerRoleName: 'anonymous',
label: 'Anonymous',
}
const queryClient = new QueryClient()
export const ApplicationContext = React.createContext<
| {
name: string
Expand Down Expand Up @@ -153,7 +155,9 @@ export const DMApplicationProvider = (props: {
loading,
}}
>
{props.children}
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
<ToastContainer />
</ApplicationContext.Provider>
)
Expand Down
66 changes: 37 additions & 29 deletions packages/dm-core/src/components/ViewCreator/ViewCreator.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { Typography } from '@equinor/eds-core-react'
import { AxiosResponse } from 'axios'
import React, { useEffect, useMemo, useState } from 'react'
import { EntityView, Loading, TAttribute, useApplication } from '../../index'
import { useQuery } from '@tanstack/react-query'
import { AxiosError } from 'axios'
import React, { useMemo, useState } from 'react'
import {
EntityView,
ErrorResponse,
Loading,
TAttribute,
useApplication,
} from '../../index'
import {
IUIPlugin,
TInlineRecipeViewConfig,
Expand Down Expand Up @@ -40,39 +47,40 @@ type TViewCreator = Omit<IUIPlugin, 'type'> & {
export const ViewCreator = (props: TViewCreator): React.ReactElement => {
const { idReference, viewConfig, onOpen, onSubmit, onChange } = props
const { dmssAPI } = useApplication()
const [isLoading, setIsLoading] = useState<boolean>(true)
const [error, setError] = useState<Error>()
const [attribute, setAttribute] = useState<TAttribute>()
const [directAddress, setDirectAddress] = useState<string>()

const reference = useMemo(
() => getTarget(idReference, viewConfig),
[idReference, viewConfig]
)
const queryKeys = ['attributes', reference, viewConfig.resolve]

useEffect(() => {
dmssAPI
.attributeGet({
address: reference,
resolve: props.viewConfig.resolve,
})
.then((response: AxiosResponse) => {
setAttribute(response.data.attribute)
setDirectAddress(response.data.address)
})
.catch((error) => setError(error))
.finally(() => setIsLoading(false))
}, [reference])
const { isPending, data } = useQuery<{
address: string
attribute: TAttribute
}>({
staleTime: 5 * 1000,
refetchOnMount: false,
queryKey: queryKeys,
queryFn: () =>
dmssAPI
.attributeGet({
address: reference,
resolve: props.viewConfig.resolve,
})
.then((response: any) => response.data)
.catch((error: AxiosError<ErrorResponse>) => setError(error)),
})

if (isLoading || !directAddress) return <Loading />
if (isPending || !data?.address) return <Loading />
if (error)
return (
<Typography>
Could not find attribute for document with id {reference} (
{error.message})
</Typography>
)
if (attribute === undefined)
if (data.attribute === undefined)
throw new Error('Unable to find type and dimensions for view')

if (viewConfig === undefined)
Expand All @@ -82,8 +90,8 @@ export const ViewCreator = (props: TViewCreator): React.ReactElement => {
if (isInlineRecipeViewConfig(viewConfig)) {
return (
<InlineRecipeView
idReference={directAddress}
type={attribute.attributeType}
idReference={data.address}
type={data.attribute.attributeType}
viewConfig={viewConfig}
onOpen={onOpen}
onSubmit={onSubmit}
Expand All @@ -95,11 +103,11 @@ export const ViewCreator = (props: TViewCreator): React.ReactElement => {
if (isReferenceViewConfig(viewConfig)) {
return (
<EntityView
type={attribute.attributeType}
idReference={directAddress}
type={data.attribute.attributeType}
idReference={data.address}
recipeName={viewConfig.recipe}
onOpen={onOpen}
dimensions={attribute.dimensions}
dimensions={data.attribute.dimensions}
showRefreshButton={viewConfig.showRefreshButton}
onSubmit={onSubmit}
onChange={onChange}
Expand All @@ -108,10 +116,10 @@ export const ViewCreator = (props: TViewCreator): React.ReactElement => {
} else if (isViewConfig(viewConfig)) {
return (
<EntityView
idReference={directAddress}
type={attribute.attributeType}
idReference={data.address}
type={data.attribute.attributeType}
onOpen={onOpen}
dimensions={attribute.dimensions}
dimensions={data.attribute.dimensions}
showRefreshButton={viewConfig.showRefreshButton}
onSubmit={onSubmit}
onChange={onChange}
Expand Down
Loading
Loading