Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use form data with custom hook in react js?

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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,
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading