Cococrunch
Cococrunch

Reputation: 67

Unable to setState regardless of making setState synchronous

I am learning about how to use synchronous setState but it is not working for my project. I want to update the state after I get the listingInfo from Axios but it does not work, the res.data, however, is working fine

class ListingItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      listingInfo: {},
      open: false,
    };
    this.getListingData(this.props.itemId);
  }

  setStateSynchronous(stateUpdate) {
    return new Promise((resolve) => {
      this.setState(stateUpdate, () => resolve());
    });
  }

  getListingData = async (item_id) => {
    try {
      const res = await axios.get(`http://localhost:5000/api/items/${item_id}`);
      console.log(res.data);//it's working
      await this.setStateSynchronous({ listingInfo: res.data });
      // this.setState({
      //   listingInfo: res.data,
      // });
      
      console.log(this.state.listingInfo);//no result
    } catch (err) {
      setAlert('Fail to obtain listings', 'error');
    }
  };

I would be really grateful for your help!

Upvotes: 0

Views: 69

Answers (1)

Cococrunch
Cococrunch

Reputation: 67

Thanks to @PrathapReddy! I used conditional rendering to prevent the data from rendering before the setState is done. I added this line of code on the rendering part:

render() {
    if (Object.keys(this.state.listingInfo).length === 0) {
      return (
        <div>
          Loading
        </div>
      );
    } else {
      return //put what you want to initially render here
    }
}

Also, there is no need to modify the setState, the normal setState will do. Hope this is useful!

Upvotes: 1

Related Questions