How to get the latest state value after using setState?

How to get the latest state value after using setState?

Content Index :

How to get the latest state value after using setState?
Tag : reactjs , By : Jonathan Bernard
Date : January 11 2021, 03:32 PM

Does that help Your code is needlessly complex. From what I understand, you want to toggle the open property to be either true or false depending on a button click. And you want your tooltip's visibility to be tied to this state.
Below is a simple example of changing state with a button click and a tooltip that will only show when open is set to true:
const Tooltip = props => {
  return (
          width: "100px",
          height: "100px",
          backgroundColor: "black",
          margin: "auto"

class App extends React.Component {
  constructor(props) {
    this.state = { open: false };
  buttonClick = () => {
    this.setState(prevState => ({ open: !prevState.open }));
  render() {
    return (
      <div className="App">
        <button onClick={this.buttonClick}>Toggle</button>
        <p>{`this.state = { open: ${this.state.open} }`}</p>
        <Tooltip hidden={this.state.open} />

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

this.setState not updating immediately, when basing setState on current state

Tag : reactjs , By : Amin Amini
Date : March 29 2020, 07:55 AM
I wish this helpful for you I wrote a few test cases, turns out the problem was elsewhere. I was using this switch-case to render different data. React Native has a feature which prevents unwanted rerendering if the data is similar to the previous data. Apparently this includes reversing and sorting the original data array. So I returned a new data array with [].concat() and it worked.

I have one this.state and i need pass in my componentDidMount with setState, how use bind(this) in setState?

Tag : javascript , By : harley.holt
Date : March 29 2020, 07:55 AM
I hope this helps you . I have that pass Bind in setState, how to do? enter image description here , You can resolve setState undefined issue in two ways
componentDidMount() {
    this.database.once("value", snapshot => {
       snapshot.forEach(data => {
          this.setState({users: data.val()})
  componentDidMount() {
     this.database.once("value", function(snapshot) {
         snapshot.forEach(function(data) {
             this.setState({users: data.val()})

setState(): Do not mutate state directly. Use setState()

Tag : javascript , By : Ernie Thomason
Date : March 29 2020, 07:55 AM
will help you 1- Don't mutate state directly use setState for that, so remove the first two lines.
2- Because setState is async and you are updating the state based on previous value, so use updater function, means pass a function in setState and use prevState value in that function.
updateDelay(prediction_arr,prediction_dep) {
  this.setState(prevState => ({
    prediction_arr: prediction_arr,
    prediction_dep: prediction_dep,
    delay_arr_cat: prediction_arr===0 ? "<15" : (prediction_arr===1 ? "[15; 45]" : ">45"),

    chartDataWake: [
      {wake: prevState.wake===84.73 ? "H" : (prevState.wake===14.78 ? "M" : "L"), delay: prediction_arr}

    chartDataTurnaround: [
      {turnaround: prevState.schedTurnd, delay: prediction_arr}

Why do I need to use setState callback to set state for second state item that relies on first item's setState finishing

Tag : javascript , By : jamerson
Date : March 29 2020, 07:55 AM
it should still fix some issue It's not that setState is asynchronous, it's a result of randomQuoteIndex being called before the state is set. This would be the case with or without asynchronous updating of state. Consider this slightly refactored version of componentDidMount:
  componentDidMount() {
      .then(response => response.json())
      .then(quotes => {
        const newState = {
          randomQuoteIndex: this.randomQuoteIndex(),
          isDoneFetching: true,
  componentDidMount() {
      .then(response => response.json())
      .then(quotes => this.setState({
          randomQuoteIndex: this.randomQuoteIndex(quotes),
          isDoneFetching: true

  randomQuoteIndex(quotes) {
    return random(0, quotes.length - 1);

Prevent using this.state within a this.setState (react/no-access-state-in-setstate)

Tag : javascript , By : yew tree
Date : March 29 2020, 07:55 AM
I wish did fix the issue. to @jonrsharpe for pointing me to appropriate documentation.
It turns out that state updates may be asynchronous. React may batch multiple setState() calls into a single update for performance. In the came of my code, I only have one value that was being updated. But, it's still a good idea to use a second form of setState that accepts a function rather then an object.
toggleDark = () => {
  const dark = !this.state.dark
  localStorage.setItem('dark', JSON.stringify(dark))

  this.setState(({ dark }) => ({ dark: !dark }))
Related Posts Related QUESTIONS :
  • Expandible TextInput to maximum number of lines in react-native
  • ReactJS - load the data before rendering the component
  • Function(method) is executing twice although only being called once
  • How can I remove a item class from a child's item in css and react?
  • React Devtools 4 DOM updates highlights
  • I am having trouble adding data to my table on submit
  • Axios post request is returning 401 unauthorised error
  • why is a React class component converted to functional component with hooks not picking up state in event handler on doc
  • How do I write a React Spring to change margin?
  • React tab doesn't appear in chrome developer tools
  • How to redirect to another component by setting up props from this component in react.js
  • Centre Buttons horizontally and vertically
  • Customize Reactive Search DateRange
  • Anyone know why my Component Keeps Remounting?
  • How to return value in component react typescript
  • RadioButton click TypeError: Cannot read property 'setState' of undefined
  • How should useDispatch be used to enforce type checking?
  • Property 'title' does not exist on type 'IntrinsicAttributes & IProps'
  • What are the disadvantages of client-only routes?
  • Dropping files or opening files from the file selector dialog box causes the React component to unmount
  • How to check if a component has been clicked after an onblur event in React
  • What should be considered as component in React
  • Updating Parents state from Child without triggering a rerender of Child in React
  • Select component is ignoring parent onClick event
  • How to add Condition inside render method in reactjs
  • How to fix form that will not allow text to be entered?
  • Cannot read property 'name' of undefined on React with my props
  • Material UI tooltip doesn't display on custom component, despite spreading props to that component
  • Unexpected output but expected view when using hooks React for toggle
  • Determine if two objects have an identical structure with Jest
  • Material ui - snackbox aria label not being read
  • Why is useState hook calling initialising value code twice?
  • React - override state by exists object properties
  • how to stop re-rendering of list items in context consumer when state changes
  • how to pass props one page to another page via react router?
  • How to display react numerical props only if they pass from the container?
  • Input in another component, error with target
  • What is the difference between props and children in Gatsby?
  • Validating conditional pairs of props with Typescript
  • React-Dropzone how convert each file to base64
  • How to change the return of a function to int?
  • Import only grid system from bootstrap to react
  • TypeScript Type for function arguments not erroring?
  • Unexpected user of comma operator no-sequences
  • React Native onChangeText like onChange in ReactJS
  • How to dynamically render an element on clicking a button
  • Cannot import components from react-bootstrap
  • How to prevent Office UI Fabric React DatePicker flyout from stealing focus when allowTextInput is true?
  • How delete item from redux state?
  • Uncaught TypeError: map is not a function In Reactjs with Firebase
  • Alternative to componentWillReceiveProps for my particular use case
  • Pokemon, API call Variable doesn't save
  • Rendered more hooks than during the previous render. when posting form data with React Hooks
  • How can I envoke <Link to=''> route transition from a custom function?
  • How to change certain div color base on number
  • Hide Navbar on some routes (React Router v5)
  • is it safe to ignore react's warning about calling the useState hook conditionally when only the parameter is conditiona
  • How to pass a function as a prop to React function component?
  • Creating a function that replace a letter with a line break
  • How to add and remove property from Redux state
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com