当多个组件使用相同的React Hook时防止多次获取

时间:2019-05-10 13:32:01

标签: reactjs react-hooks

在多个组件中使用此挂钩时,如何防止多个数据获取?当URL保持不变时,仅当searchQuery更改时,才不需要重新获取它。我还希望能够使用所有组件中的参数来调用loadPeople()

我尝试执行的操作是在执行people.data之前检查fetchData()是否已填充,但是那样loadPeople()将永远无法工作。

type UseStarWarsProps = {
    people: AsyncData<ApiStarWarsPerson[]>;
    loadPeople: (query?: string) => void;
};

export const useStarWars = (): UseStarWarsProps => {
    const [searchQuery, setSearchQuery] = useState('');
    const people: AsyncData<ApiStarWarsPerson[]> = useSelector((state: RootState) => state.starWars.people);
    const apiProxy: ApiProxyType = ApiProxy();
    let dispatch = useDispatch();

    const fetchData = async () => {
        dispatch(setLoaderStarWarsAction());
        try {
            const data = await apiProxy.getStarWarsPeople(searchQuery);
            dispatch(setStarWarsAction(data.results));
        } catch (e) {
            dispatch(setErrorStarWarsAction(e));
        }
    };

    useEffect(() => {
        fetchData();
    }, [searchQuery]);

    const loadPeople = (query?: string) => {
        setSearchQuery(query || '');
    };

    return { people, loadPeople };
};

0 个答案:

没有答案