-
Notifications
You must be signed in to change notification settings - Fork 371
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
[ui-core]: feat: add useLoadData hook for API calls #3819
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
f7e1cf8
[ui-core]: feat: add useFetch hook for API calls
ramprasadagarwal dc0984e
add the license information
ramprasadagarwal 95cb886
fix lint
ramprasadagarwal fdd2c13
lint fix
ramprasadagarwal bbdbd4a
add library
ramprasadagarwal b97d332
pin the library version
ramprasadagarwal 7a5c9d5
revert extra changes
ramprasadagarwal d5b5a2d
Merge branch 'master' of github.com:cloudera/hue into feat/useFetch-hook
ramprasadagarwal 662fb1b
revert package-lock json
ramprasadagarwal 74a99e4
Merge branch 'master' into feat/useFetch-hook
ramprasadagarwal a7ade51
fix: rename hook
ramprasadagarwal 1702fef
Merge branch 'master' of github.com:cloudera/hue into feat/useFetch-hook
ramprasadagarwal a164444
Merge branch 'feat/useFetch-hook' of github.com:cloudera/hue into fea…
ramprasadagarwal 3a4160a
fix the function name
ramprasadagarwal a2494d2
typecaste error object
ramprasadagarwal e85ce96
Merge branch 'master' into feat/useFetch-hook
ramprasadagarwal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
182 changes: 182 additions & 0 deletions
182
desktop/core/src/desktop/js/utils/hooks/useLoadData.test.tsx
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,182 @@ | ||
// Licensed to Cloudera, Inc. under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. Cloudera, Inc. licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
import { renderHook, act, waitFor } from '@testing-library/react'; | ||
import useLoadData from './useLoadData'; | ||
import { get } from '../../api/utils'; | ||
|
||
// Mock the `get` function | ||
jest.mock('../../api/utils', () => ({ | ||
get: jest.fn() | ||
})); | ||
|
||
const mockGet = get as jest.MockedFunction<typeof get>; | ||
const mockUrlPrefix = 'https://api.example.com'; | ||
const mockEndpoint = '/endpoint'; | ||
const mockUrl = `${mockUrlPrefix}${mockEndpoint}`; | ||
const mockData = { id: 1, product: 'Hue' }; | ||
const mockOptions = { | ||
params: { id: 1 } | ||
}; | ||
|
||
describe('useLoadData', () => { | ||
beforeAll(() => { | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
beforeEach(() => { | ||
mockGet.mockResolvedValue(mockData); | ||
}); | ||
|
||
afterEach(() => { | ||
jest.clearAllMocks(); | ||
}); | ||
|
||
it('should fetch data successfully', async () => { | ||
const { result } = renderHook(() => useLoadData(mockUrl)); | ||
expect(result.current.data).toBeUndefined(); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(true); | ||
|
||
await waitFor(() => { | ||
expect(mockGet).toHaveBeenCalledWith(mockUrl, undefined, expect.any(Object)); | ||
expect(result.current.data).toEqual(mockData); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(false); | ||
}); | ||
}); | ||
|
||
it('should fetch data with params successfully', async () => { | ||
const { result } = renderHook(() => useLoadData(mockUrl, mockOptions)); | ||
|
||
expect(result.current.data).toBeUndefined(); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(true); | ||
|
||
waitFor(() => { | ||
expect(mockGet).toHaveBeenCalledWith(mockUrl, mockOptions.params, expect.any(Object)); | ||
expect(result.current.data).toEqual(mockData); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(false); | ||
}); | ||
}); | ||
|
||
it('should handle fetch errors', async () => { | ||
const mockError = new Error('Fetch error'); | ||
mockGet.mockRejectedValue(mockError); | ||
|
||
const { result } = renderHook(() => useLoadData(mockUrl)); | ||
|
||
expect(result.current.data).toBeUndefined(); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(true); | ||
|
||
waitFor(() => { | ||
expect(mockGet).toHaveBeenCalledWith(mockUrl, undefined, expect.any(Object)); | ||
expect(result.current.data).toBeUndefined(); | ||
expect(result.current.error).toEqual(mockError); | ||
expect(result.current.loading).toBe(false); | ||
}); | ||
}); | ||
|
||
it('should respect the skip option', () => { | ||
const { result } = renderHook(() => useLoadData(mockUrl, { skip: true })); | ||
|
||
expect(result.current.data).toBeUndefined(); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(false); | ||
expect(mockGet).not.toHaveBeenCalled(); | ||
}); | ||
|
||
it('should call refetch function', async () => { | ||
const { result } = renderHook(() => useLoadData(mockUrl)); | ||
|
||
expect(result.current.data).toBeUndefined(); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(true); | ||
|
||
waitFor(() => { | ||
expect(mockGet).toHaveBeenCalledWith(mockUrl, undefined, expect.any(Object)); | ||
expect(result.current.data).toEqual(mockData); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(false); | ||
}); | ||
|
||
mockGet.mockResolvedValueOnce({ ...mockData, product: 'Hue 2' }); | ||
|
||
act(() => { | ||
result.current.reloadData(); | ||
}); | ||
|
||
waitFor(() => { | ||
expect(mockGet).toHaveBeenCalledTimes(2); | ||
expect(mockGet).toHaveBeenCalledWith(mockUrl, undefined, expect.any(Object)); | ||
expect(result.current.data).toEqual({ ...mockData, product: 'Hue 2' }); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(false); | ||
}); | ||
}); | ||
|
||
it('should handle URL prefix correctly', async () => { | ||
const { result } = renderHook(() => useLoadData(mockEndpoint, { urlPrefix: mockUrlPrefix })); | ||
|
||
expect(result.current.data).toBeUndefined(); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(true); | ||
|
||
waitFor(() => { | ||
expect(mockGet).toHaveBeenCalledWith(mockUrl, undefined, expect.any(Object)); | ||
expect(result.current.data).toEqual(mockData); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(false); | ||
}); | ||
}); | ||
|
||
it('should update options correctly', async () => { | ||
const { result, rerender } = renderHook( | ||
(props: { url: string; options }) => useLoadData(props.url, props.options), | ||
{ | ||
initialProps: { url: mockUrl, options: mockOptions } | ||
} | ||
); | ||
|
||
expect(result.current.data).toBeUndefined(); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(true); | ||
|
||
waitFor(() => { | ||
expect(mockGet).toHaveBeenCalledWith(mockUrl, mockOptions.params, expect.any(Object)); | ||
expect(result.current.data).toEqual(mockData); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(false); | ||
}); | ||
|
||
const newOptions = { | ||
params: { id: 2 } | ||
}; | ||
const newMockData = { ...mockData, id: 2 }; | ||
mockGet.mockResolvedValueOnce(newMockData); | ||
|
||
rerender({ url: mockUrl, options: newOptions }); | ||
|
||
waitFor(() => { | ||
expect(mockGet).toHaveBeenCalledWith(mockUrl, newOptions.params, expect.any(Object)); | ||
expect(result.current.data).toEqual(newMockData); | ||
expect(result.current.error).toBeUndefined(); | ||
expect(result.current.loading).toBe(false); | ||
}); | ||
}); | ||
}); |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
// Licensed to Cloudera, Inc. under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. Cloudera, Inc. licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
import { useCallback, useEffect, useMemo, useState } from 'react'; | ||
import { ApiFetchOptions, get } from '../../api/utils'; | ||
|
||
export type IOptions<T, U> = { | ||
urlPrefix?: string; | ||
params?: U; | ||
fetchOptions?: ApiFetchOptions<T>; | ||
skip?: boolean; | ||
}; | ||
|
||
type IUseLoadData<T> = { | ||
data?: T; | ||
loading: boolean; | ||
error?: Error; | ||
reloadData: () => void; | ||
}; | ||
|
||
const useLoadData = <T, U = unknown>(url?: string, options?: IOptions<T, U>): IUseLoadData<T> => { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. what is the use case for not passing in a url? |
||
const [localOptions, setLocalOptions] = useState<IOptions<T, U> | undefined>(options); | ||
const [data, setData] = useState<T | undefined>(); | ||
const [loading, setLoading] = useState<boolean>(false); | ||
const [error, setError] = useState<Error | undefined>(); | ||
|
||
const fetchOptionsDefault: ApiFetchOptions<T> = { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: this could be defined outside the component |
||
silenceErrors: false, | ||
ignoreSuccessErrors: true | ||
}; | ||
|
||
const fetchOptions = useMemo( | ||
() => ({ ...fetchOptionsDefault, ...localOptions?.fetchOptions }), | ||
[localOptions] | ||
); | ||
|
||
const loadData = useCallback( | ||
async (isForced: boolean = false) => { | ||
// Avoid fetching data if the skip option is true | ||
// or if the URL is not provided | ||
if ((options?.skip && !isForced) || !url) { | ||
return; | ||
} | ||
setLoading(true); | ||
setError(undefined); | ||
|
||
try { | ||
const fetchUrl = localOptions?.urlPrefix ? `${localOptions.urlPrefix}${url}` : url; | ||
const response = await get<T, U>(fetchUrl, localOptions?.params, fetchOptions); | ||
setData(response); | ||
} catch (error) { | ||
setError(error instanceof Error ? error : new Error(error)); | ||
} finally { | ||
setLoading(false); | ||
} | ||
}, | ||
[url, localOptions, fetchOptions] | ||
); | ||
|
||
useEffect(() => { | ||
loadData(); | ||
}, [loadData]); | ||
|
||
useEffect(() => { | ||
// set new options if they are different (deep comparison) | ||
if (JSON.stringify(options) !== JSON.stringify(localOptions)) { | ||
setLocalOptions(options); | ||
} | ||
}, [options]); | ||
|
||
return { data, loading, error, reloadData: () => loadData(true) }; | ||
}; | ||
|
||
export default useLoadData; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is the purpose of the I-prefix? If it is to indicate an interface, perhaps it would better to use an interface instead of type.