I made a hook useSendFormData , when i use it i get Invalid hook call.
Hook takes
data from SubmitForm
url:string,
method: post or put
success: succes message if it was success
id: not required but if item has id i is added to api call.
auth default false
Problem is it loses data on renders i dont know how to describe it better so i made console.log ss As you can see on second call i get data but later its gone...
My code for this coustom hook:
const sendFormData = async ({
formData,
url,
method,
success,
id,
auth = false,
}) => {
const setPartData = (partialData) => setData({ ...data, ...partialData });
try {
let response;
if (method === "post") {
response = await axios.post(
`${SERVER_API}api/v1/${url}/${id ?? ""}`,
formData
);
} else if (method === "put") {
response = auth
? await fetchContext.authAxios.post(
`${SERVER_API}api/v1/${url}/${id ?? ""}`,
formData
)
: await axios.post(
`${SERVER_API}api/v1/${url}/${id ?? ""}`,
formData
);
}
setPartData({
data: response.data,
loading: false,
success,
error: null,
});
} catch (err) {
const { data } = err.response;
setPartData({
error: data.error,
success: null,
loading: false,
});
}
return data;
};
return {
sendFormData,
};
};
And where is use it , it takes data from SubmitForm and make api call with it,as you can see in ss i get there undefined:
const { 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();
};
If you could help that would be awesome. If you have any optimatizaion hints for this hook please tell me.Thanks for your time.
Edit: Edit hook but doesnt return data value at the end
question from:https://stackoverflow.com/questions/65941485/coustom-hook-when-taking-data-in-next-render-lost-data