Home > Software design >  how to use form data with custom hook in react js?
how to use form data with custom hook in react js?

Time:05-07

I have my custom axios hook, to send data without files it works perfectly, but when I send files it does not recognize any data.

......
const axiosFetch = async (params) => {
const { method, url, data } = params;
try {
  setLoading(true);
  const control = new AbortController();
  setController(control);

  const res = await axios[method.toLowerCase()](url, {
    ...data,
    signal: control.signal,
  });

  setResponse(res.data);
} catch (err) {
  setError(err);
} finally {
  setLoading(false);
}
};
......

If I modify this part, the file upload works, but it loses the signal. How can I implement both properties.

   const res = await axios[method.toLowerCase()](url, data);

CodePudding user response:

For the POST, PUT, and PATCH requests data and configuration are the second and third arguments.

See Instance Methods

Try instead:

const res = await axios[method.toLowerCase()](
  url,
  data,
  { signal: control.signal }
);

For GET, DELETE, HEAD, and OPTIONS requests, omit the data argument.

const res = await axios[method.toLowerCase()](
  url,
  { signal: control.signal }
);

You'll need to split these request types out logically.

Alternatively you can use a request config:

const res = await axios({
  url,
  method: method.toLowerCase(),
  data,
  signal: control.signal,
});
  • Related