React Hooks - useFetch generalization



我有一个api,它为我提供了如下方法:

  1. searchUsersByUsername(用户名、限制)
  2. getRandomPremiumUsers(限制)
  3. getYoungUsers (maxAge,限制)

我正在实现一个钩子useFetchUsers",它将提供一个接口来访问这些方法。

这是我当前的代码:

import { useState, useEffect } from "react";
import {
searchUsersByUsername, 
getRandomPremiumUsers,
getRandomYoungUsers,
} from "../../services/firebase/api/users/search"
import { MAX_SEARCH_USERS_BY_USERNAME_TO_RETRIEVE } from "../../utils/search";
export const QUERIES = {
"SEARCH_USERS_BY_USERNAME": searchUsersByUsername,
"FETCH_RANDOM_PREMIUM_USERS": getRandomPremiumUsers,
"FETCH_RANDOM_YOUNG_USERS": getRandomYoungUsers,
};
const defaultOptions = {
query: QUERIES[0],
username: "", // optional
limit = MAX_SEARCH_USERS_BY_USERNAME_TO_RETRIEVE, // optional
};
export default function useFetchUsers(options = defaultOptions, deps) {
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(undefined);
const getUsers = async () => {
setIsLoading(true);
try {
const users = await options.query();
setUsers(users);
} catch(err) {
setError(err);
}
setIsLoading(false);
}
useEffect(getUsers, deps);
return {
users,
isLoading,
error,
getUsers
}
}

我面临的主要问题是,我不知道如何制作这个"界面"。更灵活,以便能够传递参数给我的QUERY方法。

同样,我的defaultOptions对象也不需要"username"gettrandompremiumusers "one_answers"getRandomYoungUsers".

关于如何满足类似抽象的需求,有什么想法吗?

创建方法并返回

export default function useFetchUsers() {
const initialState = {
payload: null,
error: null,
inFlight: false,
};
const [result, setResult] = useState(initialState);
const searchUsersByUsername = () => {
setResult({ payload: null, error: null, inFlight: true });
try {
const payload = fetch("api");
setResult({ payload, error: null, inFlight: false });
} catch (error) {
setResult({ payload: null, error: null, inFlight: false });
}
};
return {
...result,
searchUsersByUsername,
};
}

写一个API helper来实现取回逻辑

const api = {
user: {
searchUsersByUsername: (option) => {
return fetch(option);
},
getRandomPremiumUsers: (option) => {
return fetch(option);
},
getYoungUsers: (option) => {
return fetch(option);
},
},
};
export default function useFetchUsers() {
const initialState = {
payload: null,
error: null,
inFlight: false,
};
const [result, setResult] = useState(initialState);

const updateState = (fetcher, option) => {
setResult({ payload: null, error: null, inFlight: true });
try {
const payload = fetcher(option);
setResult({ payload, error: null, inFlight: false });
} catch (error) {
setResult({ payload: null, error: null, inFlight: false });
}
};
return {
...result,
updateState,
};
}
function App() {
const { updateState, payload } = useFetchUsers();
return (
<div
onclick={() =>
updateState(api.user.searchUsersByUsername, { username: 'name', limit: 10 })
}
>
searchUsersByUsername
</div>
);
}

所以根据你的用例你可以在API层本身实现缓存或者用上下文API扩展它

相关内容

  • 没有找到相关文章

最新更新