Joao Tonial
Joao Tonial

Reputation: 1

How to use state inside a function called by onSubmit?

I'm having an issue using state inside a function that is called by redux-form's Form component's onSubmit.

I need to access a given piece of state, tabs and currentTab. The first is an array of tabs, the second is an indicator to which tab the user currently is.

I've tried using a click event to handle the submission and it all works fine.

Passing state as a parameter does not work. eg

<Form onSubmit={() => submit(currentTab, tabs.length)}>
  ...
</Form>

it still uses the default state of 0.

I've also tried using the handleSubmit prop given to decorated components but got no luck with that.

The issue is that the state inside the function is not up to date with the actual state when the submit event occurs.

const [tabs, setTabs] = useState([])
const [currentTab, setCurrentTab] = useState(0)
console.log('outside', tabs.length); // outside 2
const submit = () => { 
  console.log('inside', tabs.length); /* inside 0  <- still the 
  default value provided to useState */
  if (tabs.length == currentTab + 1) {
    props.onSubmit();
  } else {
    handleNextTab();
  }
};
<Form onSubmit={submit}>
  ...
</Form>

Since the tabs are dynamic and can vary in length i want to be able to compare the tabs.length to the currentTab to know whether or not the user is in the last tab to trigger different actions depending on the result.

Upvotes: 0

Views: 623

Answers (2)

varoons
varoons

Reputation: 3887

You need to pass tabs as a parameter to your submit function.

Upvotes: 0

Ian
Ian

Reputation: 705

If the state is true at the time of rendering the Form, you could curry the onSubmit handler, and pass the state to the handler.

I am thinking:

<Form onSubmit={handleSubmit(tabs, currentTab)}>
  ...
</Form>

And:

const handleSubmit = (tabs, currentTab) => {
    return () => {
        // Do something with `tabs`, and `currentTab` here
    };
};

See also (related): https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback

Upvotes: 1

Related Questions