Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
Fetching data from api promise in react API

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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]);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda