Skip to content

Commit

Permalink
fix: update swr
Browse files Browse the repository at this point in the history
  • Loading branch information
Marc Pomar committed Jun 26, 2024
1 parent 4c49632 commit 5877b7a
Show file tree
Hide file tree
Showing 8 changed files with 629 additions and 73 deletions.
4 changes: 3 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ src
babel.config.js
tsconfig.json
tsconfig.tsbuildinfo
yarn.lock
yarn.lock
.test.js
jest.config.js
13 changes: 13 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module.exports = {
moduleFileExtensions: ["ts", "tsx", "js", "json"],
moduleNameMapper: {
"\\.scss$": "identity-obj-proxy",
"^@components/(.*)$": "<rootDir>/src/components/$1",
},
collectCoverageFrom: ["<rootDir>/**/*.{ts, tsx}"],
roots: ["<rootDir>"],
testRegex: "(/tests/jest/.*|(\\.|/)(test|spec))\\.(ts|tsx)$",
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
};
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,21 @@
"devDependencies": {
"@babel/preset-env": "^7.23.6",
"@babel/preset-typescript": "^7.23.3",
"@testing-library/react-hooks": "^8.0.1",
"@testing-library/dom": "^10.2.0",
"@testing-library/react": "^16.0.0",
"@types/jest": "^29.5.11",
"@types/react": "^18.2.57",
"ava": "^5.3.1",
"axios": "^1.7.2",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"nodemon": "^3.0.1",
"react": "^18.2.0",
"react-dom": "^18.3.1",
"react-test-renderer": "^18.2.0",
"semantic-release": "^22.0.6",
"swr": "^2.2.5",
"ts-jest": "^29.1.5",
"ts-node": "^10.9.1",
"typescript": "^5.2.2"
},
Expand Down
39 changes: 0 additions & 39 deletions src/useSWRPaginated.test.ts

This file was deleted.

92 changes: 92 additions & 0 deletions src/useSWRPaginated.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* @jest-environment jsdom
*/

import { act, renderHook, waitFor } from "@testing-library/react";
import { generateGetKey, useSWRPaginated } from "./useSWRPaginated";
import axios from "axios";
import { SWRConfig } from "swr";
import React from "react";
import { unstable_serialize } from "swr/infinite";

const testapi = axios.create({ baseURL: "https://api-content.faable.link" });
const fetcher = async (key) => {
const res = await testapi.get(key);
return res.data;
};

const setupWrapper =
(fallback?: any) =>
({ children }) =>
(
<SWRConfig
value={{
fetcher,
fallback,
}}
>
{children}
</SWRConfig>
);

// test("without fallback data", async () => {
// const wrapper = setupWrapper();
// const { result, waitForNextUpdate } = renderHook(
// () => useSWRPaginated(generateGetKey("/content")),
// { wrapper }
// );

// expect(result.current.items).toEqual(undefined);
// await waitForNextUpdate({ timeout: 5000 });
// expect(result.current.items.length).toEqual(29);
// });

test("with fallback data", async () => {
const key = "/content";
const data = await fetcher(key);
const fallback = {
[unstable_serialize(generateGetKey(key))]: [data],
};
const wrapper = setupWrapper(fallback);
const { result } = renderHook(() => useSWRPaginated(generateGetKey(key)), {
wrapper,
hydrate: true,
});
// await act(async () => {});
// await waitFor(() => {
// const swr = result.current;
// expect(swr.data?.length).toEqual(1);
// expect(swr.items?.length).toEqual(30);
// });
expect(result.current.data?.length).toEqual(1);
expect(result.current.items?.length).toEqual(30);
// console.log(result.current.data);
// console.log(result.current.items);
});

// test("should use counter", () => {
// let a = "hola";
// const { result } = renderHook(() =>
// useSWRPaginated(a ? generateGetKey("/demo?q=124") : null)
// );

// expect(result.current.items).toStrictEqual([]);

// expect(typeof result.current.setSize).toBe("function");
// });

// test("should use counter", () => {
// let a = "hola";
// const { result } = renderHook(() =>
// useSWRPaginated<{ name: string }>(
// a ? generateGetKey("/demo?q=124") : null,
// {
// refreshInterval: 3000,
// }
// )
// );

// expect(result.current.items).toStrictEqual([]);

// expect(typeof result.current.setSize).toBe("function");
// });
33 changes: 20 additions & 13 deletions src/useSWRPaginated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const generateGetKey = <T>(

const url = new URL(base, "https://dummy.com");

console.log("STEP2", base);
// page size
if (pageSize) {
url.searchParams.set("pageSize", pageSize.toString());
Expand All @@ -39,33 +40,39 @@ export const generateGetKey = <T>(
};
};

type SWRPaginatedResponse<T> = SWRInfiniteResponse & {
items: T[];
isEmpty: boolean;
isReachingEnd: boolean;
};

export function useSWRPaginated<T, P extends Page<T> = Page<T>>(
getKey: SWRInfiniteKeyLoader<P>,
config?: SWRInfiniteConfiguration<P, Error, BareFetcher<P>>
) {
): SWRPaginatedResponse<T> {
const swr = useSWRInfinite<P>(getKey, config);

return {
swr,
setSize: swr.setSize,
size: swr.size,
isValidating: swr.isValidating,
isLoading: swr.isLoading,
error: swr.error,
data: swr.data,
get items() {
Object.defineProperty(swr, "items", {
get: function () {
return swr.data?.map((p) => p?.results).flat();
},
get isEmpty() {
});
Object.defineProperty(swr, "isEmpty", {
get: function () {
return swr.data?.[0]?.results?.length === 0;
},
get isReachingEnd() {
});

Object.defineProperty(swr, "isReachingEnd", {
get: function () {
const empty = swr.data?.[0]?.results?.length === 0;
return empty
? true
: swr.data
? swr.data[swr.data?.length - 1]?.next == null
: false;
},
};
});

return swr as any;
}
4 changes: 3 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
"module": "CommonJS",
"resolveJsonModule": true,
"experimentalDecorators": true,
"declaration": true
"declaration": true,
"jsx": "react",
"lib": ["esnext", "dom"]
},
"include": ["src"]
}
Loading

0 comments on commit 5877b7a

Please sign in to comment.