skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. const [products, setProducts] = useState([]);
    
    useEffect(() => {
        (async () => {
            try {
                let res = await fetch("http://localhost:1337/api/categories");
                let data = await res.json(); // Await the promise
                setProducts(data);
                console.log(data);
            } catch (err) {
                alert(err);
            }
        })();
    }, []);
    

    Use Await in res.Json();

    Login or Signup to reply.
  3. 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

    const [products, setProducts] = useState([]);
    
    useEffect(() => {
        (async () => {
            try {
                let res = await fetch("http://localhost:1337/api/categories");
                let data = await res.json(); // Await the json() method
                setProducts(data);
                console.log(data);
            } catch (err) {
                alert(err);
            }
        })();
    }, []);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search