Home > Blockchain >  Fetching data from api promise in react API
Fetching data from api promise in react API

Time:11-09

I fetch data from the Company API by using a specific proxy in package.json.

this is my code:

const [products, setProducts] = useState({
        loading: false,
        data: null,
        error: false,
    });

    const apiLink = 'https://example.com/api/checkout/products/';

    useEffect(() => {
        setProducts({
            loading: true,
            data: null,
            error: false,
        });

        fetch(apiLink, {
                method: 'POST',
                body: JSON.stringify({
                    "categories": [
                        "13", "14", "4", "8"
                    ]
                })
            })
            .then(response => {
                response.json().then(data => console.log(data.products))
            })
    }, [apiLink])

but when I console.log() the data it appear like that in console:

Promise {<pending>}
   [[Prototype]]: Promise
   [[PromiseState]]: "fulfilled"
   [[PromiseResult]]: Object

and inside the [[PromiseResult]] There is the information I need to deal with it. Like: products

how can i access to this products and loop its in my page. please i need help.

because when i access to products like that:

console.log(products.data.products)

i have undefined in console.

CodePudding user response:

As described in MDN: Uploading JSON data, after receiving data from API you should handle each operation in a separate .then process.

fetch(apiLink, {
  method: 'POST',
  body: JSON.stringify({
    "categories": [
       "13", "14", "4", "8"
    ]
  })
})
.then(response => response.json())
.then(data => console.log(data.products))

CodePudding user response:

the promise is needed only in the fetch() method since it is a deferred computation, after that you can use any method to process your data

fetch(apiLink, {
  method: 'POST',
  body: JSON.stringify({
    "categories": [
       "13", "14", "4", "8"
    ]
  })
})
.then(response => response.json())
.catch(x=>console.log(x)).map(x=>console.log(x.products))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

you can learn more about promises in: https://learnjsx.com/category/2/posts/es6-promise

CodePudding user response:

You can use async/await in the useEffect

useEffect(() => {
  const init = async () => {
    setProducts({
      loading: true,
      data: null,
      error: false,
    });

    try {
      const response = await fetch(apiLink, {
        method: "POST",
        body: JSON.stringify({
          categories: ["13", "14", "4", "8"],
        }),
      });
      response = await response.json();
      // set your state after this
    } catch (e) {
      console.error(e);
    }
  };

  init();
}, [apiLink]);

  • Related