4

So I have a code like this

  const getAllProduct = async () => {
    let allProduct = "";

    let config = {
      method: "get",
      url: db_base_url + "/products/",
      headers: {
        Authorization: "Bearer " + token.access.token,
        "Content-Type": "application/json",
      },
    };

    try {
      let response = await axios(config);
      allProduct = response.data.results;
    } catch (error) {
      console.log(error);
    }
    console.log(allProduct);
    return allProduct;
  };

The console.log(allProduct) do prints an array.

The function will be called on the render method of react by

return (<div> {getAllProduct()} </div>)

I've tried to do

return (<div> {console.log(getAllProduct())} </div>

But the console.log on rendering returns to be Promise Object instead of the results array.

How can I go around this?

2
  • You can't get around this - but you shouldn't need to. It returns a promise since you don't know when your function will complete as it occurs asynchronously, once in "asynchronous mode" you can't get your value back to "synchronous mode". You'll need to await the returned Promise or use .then() on it. Commented Feb 21, 2021 at 10:30
  • You'll need to await it, and/or set the value globally. Define a variable above somewhere and set it on the return but this is async, await it. :) Commented Feb 21, 2021 at 10:31

4 Answers 4

5

async functions return a Promise which means their result is not immediately available.

What you need to do is either await the result of calling getAllProduct() function or chain a then() method call.

Looking at your code, I assume that you want to call getAllProduct() function after your component is rendered. If that's the case, useEffect() hook is where you should call your function.

You could define and call your function inside the useEffect() hook and once the data is available, save that in the local state of your component.

First define the local state of the component

const [products, setProducts] = useState([]);

Define and call the getAllProduct() function inside the useEffect() hook.

useEffect(() => {
  const getAllProduct = async () => {
    ...

    try {
      let response = await axios(config);
      allProduct = response.data.results;
       
      // save the data in the state
      setProducts(allProduct);

    } catch (error) {
      console.log(error);
    }
  };

  // call your async function
  getAllProduct();
}, []);

Finally, inside the JSX, map() over the products array and render the products in whatever way you want to render in the DOM.

return (
  <div>
    { products.map(prod => {
       // return some JSX with the appropriate data
    }) }
  </div>
);
   
Sign up to request clarification or add additional context in comments.

Comments

0

async function always return a promise you use await before call it getAllProduct()

const  res = await getAllProduct();
console.log(res) 

1 Comment

What does this do? We want to return a custom result. res is not a custom result.
0

In my case daisy chaining .then didn't work. Possibly due to fact that I had a helper JS file that held all DB related functions and their data was utilized across various React components.

What did work was daisy chaining await within an async. I modified code where it works for same Component (like in your case). But we can take same logic , put async function in different JS file and use its response in some other component.

Disclaimer : I haven't tested below code as my case was different.
useEffect( () => {
    var handleError = function (err) {
        console.warn(err);
        return new Response(JSON.stringify({
            code: 400,
            message: 'Error in axios query execution'
        }));
      };
    
      const getAllProduct = async () => {
        let allProduct = "";
        ...
    
        const response = await ( axios(config).catch(handleError));
        allProduct = await response;
        return allProduct;
      }
},[]);     

// Then inside JSX return

    getAllProduct().then( data => { 
        // Make use of data 
    });

Comments

-1

use

getAllProduct().then(res => console.log(res))

3 Comments

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
I understand. I will try harder to give an explanation
What does this even do? res is not the custom result that we want to return from our function!

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.