The way you designed your hook the fetch is done once the hook is invoked. Instead you should define a sendFormData
function inside your hook and return it along with data state (or any other variables you need). Since you want response.data
to be returned I adapted the function to return response.data
:
export const useSendFormData = () => {
const [data, setData] = useState({
error: "",
loading: true,
success: "",
data: [],
});
const sendFormData = async ({
formData,
url,
method,
success,
id,
}) => {
const setPartData = (partialData) => setData({ ...data, ...partialData });
try {
let response
if (method === "post") {
response = await axios.post(
`${SERVER_API}api/v1/${url}/${id ?? ""}`,
formData
);
setPartData({ data: response.data, success, error: null });
} else if (method === "put") {
response = await axios.post(
`${SERVER_API}api/v1/${url}/${id ?? ""}`,
formData
);
setPartData({ data: response.data, success, error: null });
}
setPartData({
loading: false,
});
return response.data
} catch (err) {
const { data } = err.response;
setPartData({
error: data.error,
success: null,
loading: false,
});
return data
}
}
return {
data, sendFormData
};
};
With that you can call your hook properly at your component body, extracting data
and sedFormData
:
// here you have your data state and sendFormData extracted
const { data, sendFormData } = useSendFormData()
const handleForm = async (info) => {
// here you have your response.data returned
const data = await sendFormData({
formData: info,
url: "auth/forgot-password",
method: "post",
success: "A password reset message has been sent to your email",
});
console.log(data);
reset();
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…