I’m using strapi in my project, but when I fetch, it gives me promise instead of json
my code :
const [products, setproducts] = useState([]);
useEffect(() => {
(async () => {
try {
let res = await fetch("http://localhost:1337/api/categories");
let data = res.json()
setproducts(data);
console.log(data)
}
catch (err) { alert(err) }
})();
}, []);
The response the Postman gave me has JSON
3
Answers
Because the
.json()
method returns a promise that resolves with the result of parsing the response body text as JSON.See: https://developer.mozilla.org/en-US/docs/Web/API/Response#instance_methods
That means you have to
await response.json()
as well.Use Await in res.Json();
you can use to await the json() method on the res object returned by fetch. json() method returns a promise as well, so you need to await it to get the data from res object