So, I'm getting the following error when trying to submit a form on React that uses a custom hook:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'url') at sendRequest (use-http.js:5:1)
Inside the form component, I have the following code (which is triggered by the form submission)
const enteredDateRef = useRef();
const enteredClientRef = useRef();
const enteredTaskRef = useRef();
const enteredTimeRef = useRef();
const renderNewTask = (data) => {
const taskData = {
id: data.name,
date: data.enteredDate,
client: data.enteredClient,
task: data.enteredTask,
time: data.enteredTime,
};
setTasks((tasks) => [taskData, ...tasks]);
};
const { sendRequest: postTask } = useHttp();
const submitTaskHandler = async (event) => {
event.preventDefault();
const newTaskData = {
Date: enteredDateRef.current.value,
Client: enteredClientRef.current.value,
Task: enteredTaskRef.current.value,
Time: enteredTimeRef.current.value,
};
postTask(
{
url: "https://myurl.com/myurl.json",
method: "POST",
body: JSON.stringify(newTaskData),
headers: { "Content-Type": "application.json" },
},
renderNewTask
);
};
And here is the custom hook:
const useHttp = (requestConfig, applyData) => {
const sendRequest = async () => {
const response = await fetch(requestConfig.url, {
method: requestConfig.method ? requestConfig.method : "GET",
headers: requestConfig.headers ? requestConfig.headers : {},
body: requestConfig.body ? JSON.stringify(requestConfig.body) : null,
});
const responseData = await response.json();
applyData(responseData);
};
return { sendRequest };
};
export default useHttp;
The custom hook is for http requests and apparently the argument is not being read when running postTask in the end. Why is this happening and how can I fix it?