简体   繁体   中英

How to use Axios with async/await syntax in react?

I want to retrieve an array from my db using axios and display it in react component. I have used componentDidMount() lifecycle method with async/await syntax as follows:

state = {
      products: []
}

async componentDidMount() {
     const res=  await axios.get(http://santacruz.clickysoft.net/api/public/home-product)
     .then(res => this.setState({products: res.data.products})
     .catch(err => console.log(err));
}

The return statement of the class component is as follows:

 return (
  <div className="wwd animated" data-animation="bounceInLeft">
    <div className="wwd-slider">
      <div className="container-fluid">
        <div className="row">
          <div className="col-md-12 nlrp">
            <div className="owl-carousel owl-theme">
              {
                this.state.product.map( product => 
                  <div className="item">
                  <img src="images/p-01.png" className="img-fluid" />
                  <div className="wwd-over">
                    <a href="#">{product.product_name}</a>
                      <p>{product.info}</p>
                  </div>
                </div>
                )}
              }
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
);

When I run this, it works fine, the state is updated and I can see all products in it but it seems that because every time the state updates, the components re renders itself and my element alignment on the web page is completely disturbed.

I want the the request to wait until all elements are fetched from db and then map it on the state only once. Can somebody tell me how to achieve this?

When I hard code all 14 items of the array in state, I can the desired aligned carousel view as follows:

在此处输入图像描述

But when I fetch data from backend using axios in the same map function, everything gets disturbed.

在此处输入图像描述

Can anyone why is this happning?

So for the example you gave, await (and also the assignment to res ) is unnecessary if you are still using .then and .catch . If you wanted to use await, the more idiomatic way would be like this:

async componentDidMount() {
     try {
         const res = await axios.get(http://santacruz.clickysoft.net/api/public/home-product)

         this.setState({products: res.data.products})
     } catch(err) {
         console.log(err)
     }
}

As to why it is causing rendering issues, well, that's because owl carousel is not compatible with react without some work. When you initialize owl carousel, it changes the DOM as it needs, which means it takes your html and modifies it quite a bit - from something like this:

<div className="owl-carousel owl-theme">
   <div className="item">
                  …
   </div>
</div>

to something like:

<div class="owl-carousel owl-theme owl-loaded owl-drag">
    <div class="owl-stage-outer"><div class="owl-stage" style="transform: translate3d(-1176px, 0px, 0px); transition: 0s; width: 4704px;">
             <div class="owl-item cloned" style="width: 186px; margin-right: 10px;"><div class="item">
              …
            </div></div>
            <div class="owl-item active" style="width: 186px; margin-right: 10px;"><div class="item">
              …
            </div></div>
            <div class="owl-item cloned" style="width: 186px; margin-right: 10px;"><div class="item">
              …
            </div></div>
        </div></div>
     <div class="owl-nav">…</div>
</div>

But then react runs an update, looks at the DOM, and says "that's not right, let me fix that" and it then sets it back to what you originally had, which removes all the work owl carousel does. So all your divs will just be normal divs stacked on top of each other, not inside the carousel. So to fix this, I'd recommend using either a carousel designed for react, or the react owl carousel package .

You should either use

axios.get(...).then(...).catch(...)

or

const result = await axios.get(...)
this.setState({products: result.data.product})

When you use await keyword, you should think of it as a synchronous operation, thus you don't need no callbacks.

UPD: It seems like you have a typo, you should assign it like that

this.setState({products: result.data.product})

There's also typo in this.state.product s .map

You can call function in componentDidMount which call the api for you

componentDidMount() { 
  this.callAxiosApi(); 
}

So, in this function call the api through axios using async/await 
if you get response then set the state, if not console the error simple is that
callAxiosApi = async () => {
 try{
    const res = await axios.get("http://santacruz.clickysoft.net/entercode hereapi/public/home-product");
    if(res) this.setState({products: res.data.products})
    }catch(err){
       err => console.log(err)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM