【发布时间】:2022-10-15 16:16:13
【问题描述】:
我正在使用外部 rest api 构建 React Native Expo App。
我创建了可重用的 axios api 调用:
// axiosAPi.js
export const axiosApi = async (method, url, obj = {}) => {
try {
switch (method) {
case 'GET':
return await axios
.get(`${baseUrl}/${url}`, config)
.then((res) => res.data)
case 'POST':
return await axios
.post(`${baseUrl}/${url}`, obj, config)
.then((res) => res.data)
case 'PUT':
return await axios
.put(`${baseUrl}/${url}`, obj, config)
.then((res) => res.data)
case 'DELETE':
return await axios
.delete(`${baseUrl}/${url}`, config)
.then((res) => res.data)
}
} catch (error) {
throw error?.response?.data?.error
}
}
我使用 react-query 创建了一个带有登录实例的钩子:
// api/index.js
export default function useApiHook() {
const login = useMutation((obj) => axiosApi('POST', `auth/login`, obj))
return { login }
}
这是登录屏幕的实现
// screens/login.js
const loginPostMutation = useApiHook()?.login
const submitHandler = (data) => {
loginPostMutation
?.mutateAsync(data)
?.then((res) => res)
.catch((err) => err)
}
当我发送正确的凭据时,会返回没有错误的数据,但是当我发送不正确的凭据时,它会在控制台中返回错误+此警告:
无效证件 在 Mutation#execute 中的 node_modules/@tanstack/query-core/build/lib/mutation.js:153:10
【问题讨论】:
标签: react-native axios expo react-query