Home > Net >  React onclick pass button api id to state
React onclick pass button api id to state

Time:03-31

I have a simple aip with an array with 4 diffrent ids. In react I've made an

with a button for each of the ids. When i click the button I whant to change the state.id and console.log the new state.id with the new specific button id value from the api.(eventualy i what to change some render depending on the button i press).

enter image description here enter image description here

I need to press two times on one of the buttons to console.log my desired id, i need the state to change on the first click.( to make some changes to some new render)

CodePudding user response:

From the React docs for setState()

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

Try logging this.state inside your render function and you will see how it actually IS happening after the first click - but your log is displaying it before the state updates.

CodePudding user response:

setState() : setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.

  • Related