Home > Mobile >  Change javascript class into a function in React app
Change javascript class into a function in React app

Time:12-20

In my React app I have the following class:

class MyClass {
  static async optin({ email }: Args) {
    return request({
      url: '/api/optin',
      method: 'POST',
      body: { email },
    });
  }
}

export default MyClass;

Then in another file I use this class like:

  try {
    await MyClass.optin({
      email: values.email,
    });
    helpers.setStatus('submitted');
  } catch {
    helpers.setErrors({ email: 'Something wrong' });
  } finally {
    helpers.setSubmitting(false);
  }

I am using only functional components, I thought it might be better to just have functions.

How do I change this class into a function and how do I use it then? Does it make scence to change it into a function anyway?

CodePudding user response:

You can export the function:

export const optin = async ({ email }: Args) => {
  return request({
    url: '/api/optin',
    method: 'POST',
    body: { email },
  });
};

And then use it with:

import { optin } from './path/to/optin';

...

try {
    await optin({ email: values.email });
}
  • Related