0

bit of an odd issue, I have an action that updates the state, but this state is only updated when the button is clicked a second time.

   function addComponent(component: Component) {
        setSelectedComponents(oldArray => [...oldArray, component])

        console.log(selectedComponents)
    }

this is called when clicking on a button

    {components.map((component) => (
                                <div
                                    key={component.name}
                                    onClick={() => addComponent(component)}
                                    className="collapse w-96 border rounded-box border-base-300 collapse-plus my-2">
                                </div>
                            ))}

console.logging the result shows that, on the first click it's still an empty array and clicking the button again shows the object inside of the array.

any idea what's going on here? this is driving me crazy.

niels van hoof
  • 469
  • 4
  • 19
  • 1
    depends on where you are `console.log`ing. see: [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – pilchard Feb 10 '22 at 14:38
  • Put the `console.log` inside a callback, which you pass as the 2nd argument to `setSelectedComponents`. Also `Components` being a variable should start with a small letter. – Nice Books Feb 10 '22 at 14:41
  • Hey, the console.log is right after the `setSelectedComponents` bit – niels van hoof Feb 10 '22 at 14:44
  • Edited the question with the up to date code version – niels van hoof Feb 10 '22 at 14:44
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – StudioTime Feb 10 '22 at 14:49
  • Hey, not sure how to refactor my code to useEffect, would someone be able to provide an example? I understand the linked question but not sure how to refactor to it. – niels van hoof Feb 14 '22 at 07:55

0 Answers0