【发布时间】:2020-01-26 01:59:02
【问题描述】:
这是我构建的useFetch 代码,它很大程度上基于关于该主题的几篇知名文章:
const dataFetchReducer = (state: any, action: any) => {
let data, status, url;
if (action.payload && action.payload.config) {
({ data, status } = action.payload);
({ url } = action.payload.config);
}
switch (action.type) {
case 'FETCH_INIT':
return {
...state,
isLoading: true,
isError: false
};
case 'FETCH_SUCCESS':
return {
...state,
isLoading: false,
isError: false,
data: data,
status: status,
url: url
};
case 'FETCH_FAILURE':
return {
...state,
isLoading: false,
isError: true,
data: null,
status: status,
url: url
};
default:
throw new Error();
}
}
/**
* GET data from endpoints using AWS Access Token
* @param {string} initialUrl The full path of the endpoint to query
* @param {JSON} initialData Used to initially populate 'data'
*/
export const useFetch = (initialUrl: ?string, initialData: any) => {
const [url, setUrl] = useState<?string>(initialUrl);
const { appStore } = useContext(AppContext);
console.log('useFetch: url = ', url);
const [state, dispatch] = useReducer(dataFetchReducer, {
isLoading: false,
isError: false,
data: initialData,
status: null,
url: url
});
useEffect(() => {
console.log('Starting useEffect in requests.useFetch', Date.now());
let didCancel = false;
const options = appStore.awsConfig;
const fetchData = async () => {
dispatch({ type: 'FETCH_INIT' });
try {
let response = {};
if (url && options) {
response = await axios.get(url, options);
}
if (!didCancel) {
dispatch({ type: 'FETCH_SUCCESS', payload: response });
}
} catch (error) {
// We won't force an error if there's no URL
if (!didCancel && url !== null) {
dispatch({ type: 'FETCH_FAILURE', payload: error.response });
}
}
};
fetchData();
return () => {
didCancel = true;
};
}, [url, appStore.awsConfig]);
return [state, setUrl];
}
这似乎工作正常,除了一个用例:
想象一个新的客户名称或用户名或电子邮件地址被输入 - 必须检查一些数据以查看它是否已经存在以确保这些内容保持唯一性。
因此,例如,假设用户输入“我的现有公司”作为公司名称,并且该公司已经存在。他们输入数据并按Submit。此按钮的 Click 事件将被连接,以便调用对 API 端点的异步请求 - 如下所示:companyFetch('acct_mgmt/companies/name/My%20Existing%20Company')
然后组件中将有一个useEffect 构造,它将等待响应从端点返回。这样的代码可能如下所示:
useEffect(() => {
if (!companyName.isLoading && acctMgmtContext.companyName.length > 0) {
if (fleetName.status === 200) {
const errorMessage = 'This company name already exists in the system.';
updateValidationErrors(name, {type: 'fetch', message: errorMessage});
} else {
clearValidationError(name);
changeWizardIndex('+1');
}
}
}, [companyName.isLoading, companyName.isError, companyName.data]);
在上面的代码中,如果公司名称存在,则会显示错误。如果它尚不存在,则此组件所在的向导将前进。这里的关键点是处理响应的所有逻辑都包含在useEffect 中。
除非用户连续两次输入相同的公司名称,否则一切正常。在这种特殊情况下,companyFetch 的 useFetch 实例中的 url 依赖项不会更改,因此不会向 API 端点发送新请求。
我可以想出几种方法来尝试解决这个问题,但它们看起来都像是 hack。我在想其他人一定遇到过这个问题,很好奇他们是如何解决的。
【问题讨论】:
标签: reactjs asynchronous react-hooks use-effect