2

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:

enter image description here

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

enter image description here

Can anyone why is this happning?

5
  • Hi Emma, Can you put it on Codesandbox or Github where we can see the actual code? Commented May 4, 2020 at 22:35
  • When you hardcoded the results, did you use the same json data, and did you set the state using this.setState in componentDidMount? Commented May 4, 2020 at 22:42
  • Yes the same JSON data, I used postman to run the api and then pasted the array result from there directly into the state of the element. So i didn't need setState at that time Commented May 4, 2020 at 23:08
  • Ok, I think I understand the problem now. I updated my answer. Commented May 5, 2020 at 16:14
  • And had you still used setState, you might have noticed the same issue :). It helps to only change one thing at a time when debugging, but I probably would have done the same thing :D. Commented May 6, 2020 at 20:15

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I ve added the return block of the component as well, if you could please have a look and tell me if I am missing out something.
Everything looks kosher, as far as I can tell... you will get a blank carousel until your items load, but they should load the same as any other way... Also, you don't have a key for your product in the carousel, so react will complain, because it doesn't know what component to re-use. set the key of your .item div to a unique product identifier.
To diagnose the issue, we'll probably need to see the page in action so we can look at it with the browser developer tools. It's probably an odd css issue.
Oh, no, it could be owl carousel doesn't play nice with react. It's a jQuery plugin, so it might have issues with react...
1

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.products.map

3 Comments

I tried this too but it did'nt work that's why I thought maybe promises would work
If you can get promises to work, then async/await should also work. They are in fact two different ways to work with promises.
Oh okay the problem is with the return block then I guess. I ve added the return block of the component as well, if you could please have a look and tell me if I am missing out something.
1

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)
    }
}

1 Comment

This answer will be better if it has explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.