Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Dec 18, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 10 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: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 0.11.0 ( September 14, 2020 )

### Added

- Add useThing and useDataset hooks

## 0.9.8 ( September 9, 2020 )

### Added
Expand Down
13 changes: 10 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@inrupt/solid-ui-react",
"version": "0.10.1",
"version": "0.11.0",
"description": "Set of UI libraries using @solid/core",
"main": "dist/index.js",
"types": "dist/src/index.d.ts",
Expand Down Expand Up @@ -88,6 +88,7 @@
"@inrupt/solid-client": "^0.2.0",
"@inrupt/solid-client-authn-browser": "^0.1.1",
"@types/react-table": "^7.0.22",
"react-table": "^7.5.0"
"react-table": "^7.5.0",
"swr": "^0.3.2"
}
}
36 changes: 27 additions & 9 deletions src/context/datasetContext/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@
import * as React from "react";
import { RenderResult, render, waitFor } from "@testing-library/react";
import * as SolidFns from "@inrupt/solid-client";
import useDataset from "../../hooks/useDataset";
import DatasetContext, { DatasetProvider } from "./index";

jest.mock("../../hooks/useDataset");

let documentBody: RenderResult;

const mockUrl = "https://some-interesting-value.com";
Expand Down Expand Up @@ -119,6 +122,10 @@ function ExampleComponentWithDatasetUrl(): React.ReactElement {

describe("Testing DatasetContext", () => {
it("matches snapshot with Dataset provided", () => {
(useDataset as jest.Mock).mockReturnValue({
dataset: undefined,
error: undefined,
});
documentBody = render(
<DatasetProvider dataset={mockDataSetWithResourceInfo}>
<ExampleComponentWithDataset />
Expand All @@ -129,7 +136,10 @@ describe("Testing DatasetContext", () => {
});

it("matches snapshot when fetching fails", async () => {
jest.spyOn(SolidFns, "fetchLitDataset").mockRejectedValue(null);
(useDataset as jest.Mock).mockReturnValue({
dataset: undefined,
error: "Error",
});

documentBody = render(
<DatasetProvider datasetUrl="https://some-broken-resource.com">
Expand All @@ -141,6 +151,10 @@ describe("Testing DatasetContext", () => {
});

it("matches snapshot when fetching", async () => {
(useDataset as jest.Mock).mockReturnValue({
dataset: undefined,
error: undefined,
});
documentBody = render(
<DatasetProvider
datasetUrl="https://some-broken-resource.com"
Expand All @@ -156,21 +170,25 @@ describe("Testing DatasetContext", () => {
});

describe("Functional testing", () => {
it("Should call fetchLitDataset", async () => {
jest
.spyOn(SolidFns, "fetchLitDataset")
.mockResolvedValue(mockDataSetWithResourceInfo);
it("Should call useDataset", async () => {
(useDataset as jest.Mock).mockReturnValue({
dataset: mockDataSetWithResourceInfo,
error: undefined,
});

render(
<DatasetProvider datasetUrl={mockUrl}>
<ExampleComponentWithDatasetUrl />
</DatasetProvider>
);
expect(SolidFns.fetchLitDataset).toHaveBeenCalled();
expect(useDataset).toHaveBeenCalled();
});
it("When fetchLitDataset fails, should call onError if passed", async () => {
it("When useDataset return an error, should call onError if passed", async () => {
(useDataset as jest.Mock).mockReturnValue({
dataset: undefined,
error: "Error",
});
const onError = jest.fn();
(SolidFns.fetchLitDataset as jest.Mock).mockRejectedValue(null);
render(
<DatasetProvider
onError={onError}
Expand All @@ -179,6 +197,6 @@ describe("Functional testing", () => {
<ExampleComponentWithDatasetUrl />
</DatasetProvider>
);
await waitFor(() => expect(onError).toHaveBeenCalled());
await waitFor(() => expect(onError).toHaveBeenCalledWith("Error"));
});
});
51 changes: 10 additions & 41 deletions src/context/datasetContext/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,10 @@
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import React, {
createContext,
ReactElement,
useState,
useEffect,
useCallback,
useContext,
} from "react";
import {
fetchLitDataset,
LitDataset,
WithResourceInfo,
UrlString,
} from "@inrupt/solid-client";
import React, { createContext, ReactElement } from "react";
import { LitDataset, WithResourceInfo, UrlString } from "@inrupt/solid-client";

import SessionContext from "../sessionContext";
import useDataset from "../../hooks/useDataset";

export interface IDatasetContext {
dataset: LitDataset | (LitDataset & WithResourceInfo) | undefined;
Expand Down Expand Up @@ -68,35 +56,16 @@ export const DatasetProvider = ({
datasetUrl,
loading,
}: RequireDatasetOrDatasetUrl): ReactElement => {
const { fetch } = useContext(SessionContext);
const [dataset, setDataset] = useState<
LitDataset | (LitDataset & WithResourceInfo) | undefined
>(propDataset);
const { dataset, error } = useDataset(datasetUrl);

const fetchDataset = useCallback(
async (url: string) => {
try {
const resource = await fetchLitDataset(url, { fetch });
setDataset(resource);
} catch (error) {
if (onError) {
onError(error);
}
}
},
[onError, fetch]
);

useEffect(() => {
if (!dataset && datasetUrl) {
// eslint-disable-next-line no-void
void fetchDataset(datasetUrl);
}
}, [dataset, datasetUrl, fetchDataset]);
if (error && onError) {
onError(error);
}

const datasetToUse = propDataset ?? dataset;
return (
<DatasetContext.Provider value={{ dataset }}>
{dataset ? children : loading || <span>Fetching data...</span>}
<DatasetContext.Provider value={{ dataset: datasetToUse }}>
{datasetToUse ? children : loading || <span>Fetching data...</span>}
</DatasetContext.Provider>
);
};
114 changes: 114 additions & 0 deletions src/hooks/useDataset/index.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* Copyright 2020 Inrupt Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import * as React from "react";
import { renderHook } from "@testing-library/react-hooks";
import { SWRConfig, cache } from "swr";
import * as SolidFns from "@inrupt/solid-client";
import { Session } from "@inrupt/solid-client-authn-browser";
import SessionContext from "../../context/sessionContext";
import useDataset from ".";

describe("useDataset() hook", () => {
const mockDatasetIri = "https://mock.url";
const mockDataset = SolidFns.mockSolidDatasetFrom(mockDatasetIri);
const mockGetSolidDataset = jest
.spyOn(SolidFns, "getSolidDataset")
.mockResolvedValue(mockDataset);
const mockFetch = jest.fn();
const wrapper = ({ children }: { children: React.ReactNode }) => (
<SessionContext.Provider
value={{
fetch: mockFetch,
sessionRequestInProgress: true,
session: {} as Session,
}}
>
<SWRConfig value={{ dedupingInterval: 0 }}>{children}</SWRConfig>
</SessionContext.Provider>
);

afterEach(() => {
jest.clearAllMocks();
cache.clear();
});

it("should call getSolidDataset with given Iri", async () => {
const { result, waitFor } = renderHook(() => useDataset(mockDatasetIri), {
wrapper,
});

expect(mockGetSolidDataset).toHaveBeenCalledTimes(1);
expect(mockGetSolidDataset).toHaveBeenCalledWith(mockDatasetIri, {
fetch: mockFetch,
});
await waitFor(() => expect(result.current.dataset).toBe(mockDataset));
});

it("should call getSolidDataset with given options", async () => {
const newMockFetch = jest.fn();
const mockAdditionalOption = "additional option";
const mockOptions = {
fetch: newMockFetch,
additionalOption: mockAdditionalOption,
};

const { result, waitFor } = renderHook(
() => useDataset(mockDatasetIri, mockOptions),
{
wrapper,
}
);

expect(mockGetSolidDataset).toHaveBeenCalledTimes(1);
expect(mockGetSolidDataset).toHaveBeenCalledWith(mockDatasetIri, {
fetch: newMockFetch,
additionalOption: mockAdditionalOption,
});
await waitFor(() => expect(result.current.dataset).toBe(mockDataset));
});

it("should return error if getSolidDataset call fails", async () => {
mockGetSolidDataset.mockRejectedValue(new Error("async error"));

const { result, waitFor } = renderHook(() => useDataset(mockDatasetIri), {
wrapper,
});

expect(mockGetSolidDataset).toHaveBeenCalledTimes(1);
expect(mockGetSolidDataset).toHaveBeenCalledWith(mockDatasetIri, {
fetch: mockFetch,
});
await waitFor(() =>
expect(result.current.error.message).toBe("async error")
);
});

it("should return dataset undefined if uri is not defined", async () => {
const { result, waitFor } = renderHook(() => useDataset(null), {
wrapper,
});

expect(mockGetSolidDataset).toHaveBeenCalledTimes(0);

await waitFor(() => expect(result.current.dataset).toBeUndefined());
});
});
50 changes: 50 additions & 0 deletions src/hooks/useDataset/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Copyright 2020 Inrupt Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { useContext } from "react";
import useSWR from "swr";
import {
getSolidDataset,
SolidDataset,
WithResourceInfo,
} from "@inrupt/solid-client";
import SessionContext from "../../context/sessionContext";

export default function useDataset(
datasetIri: string | null | undefined,
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
options?: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): { dataset: (SolidDataset & WithResourceInfo) | undefined; error: any } {
const { fetch } = useContext(SessionContext);
const { data, error } = useSWR(
datasetIri ? [datasetIri, options, fetch] : null,
() => {
const requestOptions = {
fetch,
...options,
};
// useSWR will only call this fetcher if datasetUri is defined
return getSolidDataset(datasetIri as string, requestOptions);
}
);
return { dataset: data, error };
}
Loading