my custom hooks :
import { useContext, useState } from "react";
import { AppContext } from "../context/app.context";
const usePostAxios = (url) => {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const { setUrl, token } = useContext(AppContext);
const postData = async (data) => {
try {
setIsLoading(true);
axios.defaults.headers.common["X-Authreq"] = token;
await axios
.post(`${setUrl}/${url}`, data)
.then(({ data }) => {
setData(data);
})
.catch((err) => {
setError(err.response || err.request);
});
setIsLoading(false);
} catch (err) {
console.log(err);
}
};
return [isLoading, postData, data, error];
};
export { usePostAxios };
for posting data :
const [isPosting, postFun, res, err] = usePostAxios("/apidet/EmpLog");
const handleSubmit = async (val) => {
await postFun({
UserName: val.email,
password: val.pass,
});
if (res) {
const { Apd, Apt } = res.ResponseData;
dispatch({ type: "APP-LOGIN", token: `${Apd}:${Apt}` });
setIsError(false);
navigate("Home");
return;
} else {
setIsError(true);
return;
}
};
then why my code is getting in else block and getting error but when i press submit button again the code run successfully and my login process success
so why is my code not running on first try ?
am i doing something stupid ?
Well, wrote in this way, basically, when this this code is excecuted
if(res) {
// Something to do with result
}
the variable res has null as value, initially.
You should check for changes in res with useEffect instead, like:
useEffect(()=> {
if(res) {
// Something to do with result
}
}, [res])