Skip to content

Commit

Permalink
feat: 🎸 support automatic query
Browse files Browse the repository at this point in the history
  • Loading branch information
ariesjia committed Feb 1, 2020
1 parent e086814 commit fbedb7c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
31 changes: 29 additions & 2 deletions src/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, {useState} from "react";
import render, { act } from 'hooks-test-util'
import usePromiseCall from '../index'

Expand Down Expand Up @@ -115,7 +115,7 @@ describe("usePromiseCall test",() => {
})
expect(query).toBeCalledWith(parameter);
})
it('should suport dependent promise', async () => {
it('should support dependent promise', async () => {
const product = {
id: 1,
name: 'product name'
Expand All @@ -138,4 +138,31 @@ describe("usePromiseCall test",() => {
expect(query1).toBeCalledWith('id');
expect(query2).toBeCalledWith(product.id);
})
it('should run async method when dependency parameters is change', async () => {
const getProducts = jest.fn().mockResolvedValue(null)
const productId = 'id';
const { container } = render(() => {
const [query, setQuery] = useState('')
const call = usePromiseCall(
getProducts,
[productId, query]
)
return {
call,
setQuery
}
})
expect(getProducts).toBeCalledWith(productId, "");
await act(async () => {
await flushPromises();
})
act(() => {
container.hook.setQuery('name')
})
expect(getProducts).toHaveBeenCalledTimes(2);
expect(getProducts).toHaveBeenNthCalledWith(2, productId, "name");
await act(async () => {
await flushPromises();
})
})
})
12 changes: 10 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { useState, useRef, useCallback, useEffect } from 'react';
import {useCallback, useEffect, useRef, useState} from 'react';

const errorSymbol = Symbol()

export interface usePromiseCallOptions {
interval?: number
}

function getParamArray(params: any) {
return Array.isArray(params) ? params : [params];
}

const usePromiseCall = <T = any, K = any>(
asyncMethod: (...args: any[]) => Promise<any>,
parameters?: any,
Expand Down Expand Up @@ -37,7 +42,7 @@ const usePromiseCall = <T = any, K = any>(
);
const paramsRef = useRef();
const load = (requestParams: any) => {
const params = Array.isArray(requestParams) ? requestParams : [requestParams];
const params = getParamArray(requestParams);
dispatch({
loading: true,
});
Expand Down Expand Up @@ -85,6 +90,9 @@ const usePromiseCall = <T = any, K = any>(
};
useEffect(() => {
revalidate();
}, getParamArray(params));

useEffect(() => {
return () => {
didCancel.current = true;
};
Expand Down

0 comments on commit fbedb7c

Please sign in to comment.