I’m attempting to create a reusable callback function for axios post requests based on this answer. The issue I’m running into now is that the destructured callback function is not being recognized in the component I’m attempting to use it in. Here is the component:
const AddParameterTest = ({ params, tankId }) => {
const [date, setDate] = useState(parseAbsoluteToLocal(moment().format()));
const [selectedParam, setSelectedParam] = useState(params[0]);
const [value, setValue] = useState("");
const valueRef = useRef();
const { handlePost, status, error, response, loading } = axiosPost();
^This should be a function
const onChange = (e) => {
setValue(e.target.value);
};
const clickHandler = () => {
const test = {
param_id: selectedParam.id,
param_value: value,
test_date: moment(date).format("YYYY-MM-DD HH:mm:ss"),
tank_id: tankId
}
const res = handlePost("api/tests/newTest", test); <--Error here on attempting to click the button
}
return (
<>
<ParamList params={params} selectedParam={selectedParam} onSelect={setSelectedParam} />
<ParamValue value={value} onChange={onChange} ref={valueRef} />
<MyDatePicker aria-label='date' value={date} onChange={setDate} />
<Button title="Log" onClick={clickHandler} />
</>
)
}
export default AddParameterTest
Here is the js file for the util:
export const axiosPost = async () => {
const [response, setResponse] = useState(null);
const [status, setStatus] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const { token } = useAuth();
const handlePost = useCallback(async (url, data) => {
setLoading(true);
try {
console.log("Data", data);
console.log("url", url);
const res = await axios.post(`${url}`, JSON.stringify(data),
{
headers: {
Authorization: `Bearer ${token}`,
"Content-type": "application/json"
}
}
)
setResponse(res?.data);
}
catch(e) {
setError(e);
}
finally {
setLoading(false);
}
}, []);
return { handlePost, status, error, response, loading }
}
Still rather messy but hoping that if I can figure out the issue, I can start to clean things up.
Any idea why it won’t recognize the handlePost as a function in the component? Is it even possible and the post I followed above is deprecated?



