简体   繁体   中英

How should I refactor this code to prevent function was used before it was defined

I'm getting this error 'subscribe' was used before it was defined.eslint(no-use-before-define) here:

    const { values, handleChange, handleSubmit } = useForm(subscribe);

    function subscribe() {
        axios.post(fAction, values, {headers: {'Accept': 'application/json'}} )
        .then((response) => {
            document.querySelector('#js-response-newsletter-message > p').innerText = response.data.message;
        });
    }

What should be the approach to follow here?

I tried to switch function with const however, I'll have the same problem since I'm using value inside subscribe().

useForm() is being used from another file and it's called after submitting a form (callback() -> subscribe()):

  const handleSubmit = (event) => {
    if (event) event.preventDefault();
    if (values.email !== undefined && values.email !== '') {
      callback(event);
    }
  };

What you can do, if you don't want to disable any rules, is declare function up front. Something like this:

var subscribe;

const { values, handleChange, handleSubmit } = useForm(subscribe);

function subscribe() {
  axios.post(fAction, values, {headers: {'Accept': 'application/json'}} )
        then((response) => {
    document.querySelector('#js-response-newsletter-message > p').innerText = 
        response.data.message;
    });
 }

example in ESLint editor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM