-1

I want to update state based on the response of fetch() function but i am unable to get the value instead getting Promise {}.If i console.log() the value is correct there.

state.product = fetch("https://fakestoreapi.com/products/2")
.then((res) => res.json()
.then((json) => {
        console.log(json); // Correct value
         return json;
       })
     );
     console.log(state.product); // Promise {<pending>}

1 Answers1

2

Fetch return a Promise that resolves to a Response object.

Your second console.log evaluate to a Promise because at this time the Promise has not resolved yet.

Maybe you can try the following :

async function getProduct(id) {
  return fetch(`https://fakestoreapi.com/products/${id}`)
    .then((res) => res.json())
    .then((data) => data);
}

const product = await getProduct(2);
console.log(product);
paulin-crtn
  • 325
  • 2
  • 9
  • await outside async function is invalid. Have you tried to run? – Gaganpreet Singh Dec 30 '22 at 06:45
  • By default, Node.js treats JS code as CommonJS modules. Add `"type": "module"` to your `package.json` file to use ES modules (JS standard). No need with React or Vue as they use Babel under the hood to compile the code. – paulin-crtn Dec 30 '22 at 09:12