Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set loading state before and after an action in a React class component

Tags:

reactjs

jsx

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.

like image 720
Chen Avatar asked Apr 12 '17 12:04

Chen


People also ask

How do you set state in class component in React?

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.

How do you manage loading state in React?

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.

How do you wait for state change in React?

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.


1 Answers

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

like image 129
Tejas Rao Avatar answered Sep 21 '22 04:09

Tejas Rao