3

I'm having a real hard time trying to wait for state change. I'm using react hooks and context.

Basically, I have a custom dropdown, no form elements used here. On click, it will run a function to change the state of two parameters:

// IdeaFilters.js
const organizationContext = useOrganization();
const { organization, filterIdeas, ideas, loading } = organizationContext;

const [filter, setFilter] = useState({
    statusId: "",
    orderBy: "voteCount"
  });

  // Build the parameters object to send to filterIdeas
  const onClick = data => {
    setFilter({ ...filter, ...data });
    filterIdeas(filter);
  };

So the onClick is attached to a dropdown in the render method:

First dropdown:
<Dropdown.Item onClick={() => onClick({ orderBy: "popularityScore" })}>Popularity</Dropdown.Item>

Second dropdown:
<Dropdown.Item key={status.id} onClick={() => onClick({ statusId: status.id })}>
  {status.name}
</Dropdown.Item>

fetchIdeas() basically runs a function available in my context, that builds those parameters for my axios request. Every time I click, it requires two clicks for the idea to run. Sometimes it runs as expected, but most of the time it takes two clicks.

Any reason why I'm running into this issue?

Any help will be really appreciated!

Sananes
  • 131
  • 2
  • 9
  • I doesn't used hooks, but in React state, after update state I executed function, like that: ```this.setState({my_var: 'new_value'},() =>{console.log(this.stste.my_var);});``` – Peter Dec 22 '19 at 10:46

1 Answers1

7

Try this

const onClick = data => {
  const newFilter = { ...filter, ...data }
  setFilter(newFilter)
  filterIdeas(newFilter)
}

Instead of

const onClick = data => {
  setFilter({ ...filter, ...data })
  filterIdeas(filter)
}

In React setState is asynchronous, I guess that was your problem. Try the code above, if it works and you don't fully understand, please comment below I'll edit the answer to explain more clearly. Read my other answer here (yet in the case your problem is asynchronous setState) about how to handle async setState.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Loi Nguyen Huynh
  • 8,492
  • 2
  • 29
  • 52