Updating state of a class inside a function in React

react hooks
react setstate
useeffect react
react update state
react, ( usestate)
react class component
react state vs props
react setstate function

I am trying to update the state of this class with the array of objects stored in the variable childData. However, when I use setState({childData: childData)}, and use it later on by calling this.state.childData, it is undefined, so it never updates the states with the information.

class Users extends React.Component {
    state = {
        childData: ""
    }

   retrieve = () => {
       let childData;
       var leadsRef = database.ref('users');
       leadsRef.on('value', function(snapshot) {
           childData = snapshot.val();
           console.log(childData)
           this.setState({
               childData: childData
           })
       });
    }

    componentDidMount() {
        this.retrieve()
    }

    render() {
        return(
            <div>
            <h3>These are all the users in the app</h3>
            {console.log(this.state.childData)}
            </div>
        )
    }
}

export default Users

You have a couple issues going on. First, you do indeed need to set state within the callback function. However, as is, you'll hit an infinite loop. That's because you shouldn't be performing the async function in the render method. Instead, do it in the componentDidMount method so it only fires when the component mounts.

class Users extends React.Component {
    state = {
        childData: ""
    }

   retrieve = () => {
       let childData;
       var leadsRef = database.ref('users');
       leadsRef.on('value', snapshot => {
           childData = snapshot.val();
           console.log(childData)
           this.setState({
               childData: childData
           })
       });
    }

    componentDidMount() {
        this.retrieve()
    }

    render() {
        return(
            <div>
            <h3>These are all the users in the app</h3>
            {console.log(this.state.childData)}
            </div>
        )
    }
}

export default Users

State and Lifecycle – React, You can convert a function component like Clock to a class in five steps: Inside it, the Clock component schedules a UI update by calling setState() with an� In a class, we need to call this.setState () to update the count state: <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button>. In a function, we already have setCount and count as variables so we don’t need this: <button onClick={() => setCount(count + 1)}> Click me </button>.

Try setting state inside the leadsRef.on callback function. For example:

leadsRef.on('value', snapshot => {
    const childData = snapshot.val()
    this.setState({childData})
})

Using the State Hook – React, class. Now you can use a Hook inside the existing function component. setState in a class, updating a state variable always replaces it instead of merging it. Inside it, the Clock component schedules a UI update by calling setState () with an object containing the current time. Thanks to the setState () call, React knows the state has changed, and calls the render () method again to learn what should be on the screen.

Use this.setState in your callback. The code you are executing is non blocking so this.setState will be executed before you retrieved childDate.

Also make you callback function an arrow function.

Is this helpfull, I am not sure if it is correct.

Component State – React, What is the difference between passing an object or a function in setState ? Passing an update function allows you to access the current state value inside the� React sends the state update operation (performed by the function returned by useState) to a queue to be processed React determines it needs to re-render the component React resets the current Hook variable and calls your component

React.Component – React, React lets you define components as classes or functions. Components defined as An update can be caused by changes to props or state. These methods are below them in the tree. An error boundary can't catch an error within itself. As of React v16.8, function-based components have a lot more capability which includes the ability to manage state. In this post we are going to go through how we can use the Reacts useState function to manage state within a strongly-typed functional component with TypeScript.

react use state inside function Code Example, Get code examples like "react use state inside function" instantly right from your google search results with the class Example extends React. You can add state to a component by calling React’s useState Hook. A Hook is a kind of function that lets you “hook into” React features. For example, useState is a Hook that lets you add state to function components. You can learn more about other kinds of Hooks in the React documentation.

A guide to useState in React, There are two types of components in React: class and functional components. is the state variable and the second element is a function to update the conditions, or nested functions because React relies on the order in� Passing an update function allows you to access the current state value inside the updater. Since setState calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting:

Comments
  • What's being logged on console.log(childData) inside leadsRef.on('value'
  • an array of two objects with two users' information. When I comment out this.setState(childData: childData), that is what I get. However, when I leave that setState(childData:childData), I don't get the state to update AND get that same thing (the array of two objects over 50 times) and this error message <Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.>
  • The only reason you are having an issue is that the value of this is different when you use function instead of an arrow function. The answer works because it’s using an arrow function, otherwise your solution is fine.
  • I tried this, and the value is still undefined in the return statement this.state.childData
  • You saw where I moved setState to?
  • Sorry, an extra setState got into my answer. Can you try again?
  • I only see one setState in the code, it still doesn't work
  • @JoscandyNunez I made an update to change to an arrow function in the callback to make sure this is referring to the component.
  • I tried that, and I get this error <TypeError: Cannot read property 'setState' of null>
  • when I add it there, it gives me this error <TypeError: Cannot read property 'setState' of null>
  • If you make it an arrow function, does it work then?
  • it did ! also called this.retrieve() in componentDidMount() , thank you!