0

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?

1 Answers1

1

Since definition of sendRequest doesn't have any params and you aren't passing config to hook, requestConfig is undefined even if you pass it to postTask.

You have to remove params to useHttp hook and add these to sendRequest function inside hook as below

const useHttp = () => { 
    const sendRequest = async (requestConfig, applyData) => {
    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 };
};
Sreekar
  • 226
  • 1
  • 5
  • That did the trick. I was using useHttp directly for other requests I couldn't figure out why it wasn't working on this specific scenario. Thanks. – Lucas Vidal Aug 03 '22 at 11:53