I have function which dispatched an action. I would like to display a loader before and after the action. I know that react composing the object passed to setState
. the question is how can I update the property in async way:
handleChange(input) { this.setState({ load: true }) this.props.actions.getItemsFromThirtParty(input) this.setState({ load: false }) }
Basically, it all worked great if I put this property as part of the application state (using Redux), but I really prefer to bring this property to the component-state only.
Syntax: We can use setState() to change the state of the component directly as well as through an arrow function. Example 1: Updating single attribute. We set up our initial state value inside constructor function and create another function updateState() for updating the state.
Managing the react loading state can be a bit annoying, we need to set it to isLoading before fetching, then set it back to false after it is done. Then we also need to set it up to the button so we can show the loading state, or give some text as an indicator.
Use the useEffect hook to wait for state to update in React. You can add the state variables you want to track to the hook's dependencies array and the function you pass to useEffect will run every time the state variables change.
you can wrap the setState in a Promise and use async/await as below
setStateAsync(state) { return new Promise((resolve) => { this.setState(state, resolve) }); } async handleChange(input) { await this.setStateAsync({ load: true }); this.props.actions.getItemsFromThirtParty(input); await this.setStateAsync({ load: false }) }
Source: ASYNC AWAIT With REACT
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With