✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Error in accessing response data with fetch and HTTP API, resolved with correct syntax.

15 replies
Last updated: Jan 3, 2022
trying to do a simple fetch with the HTTP API, but I'm getting an error of Uncaught ReferenceError: result is not defined
at window.onload ((index):28). How do I access the response data?
Jan 3, 2022, 5:23 PM
I believe you need to call
.then(res => res.json())
 first?
Jan 3, 2022, 5:25 PM
I tried adding that, didnt work. tried editing "result" to "res" too, that also didn't work
.then(res => res.json())

.then(console.log(res))
Jan 3, 2022, 5:27 PM
user S
now it says Uncaught ReferenceError: res is not defined
at window.onload
Jan 3, 2022, 5:28 PM
How does your code look like now?
Jan 3, 2022, 5:34 PM
window.onload=function(){
            let encodedQuery = encodeURIComponent('[_type == "senator"]');
                fetch(`<https://6dyl9k59.api.sanity.io/v2021-01-01/data/query/production?query=*${encodedQuery}>`)
                    .then(res => res.json())
                    .then(console.log(result))
            };
Jan 3, 2022, 5:34 PM
still says result isn't defined
Jan 3, 2022, 5:35 PM
user S
also, if I add
let result;
above the function, then it just returns undefined.
Jan 3, 2022, 5:41 PM
user S
also, if I add
let result;
then it just returns undefined.
Jan 3, 2022, 5:41 PM
Do you get any error messages in the console? Have you added the domain you’re loading this from to CORS origins?
Jan 3, 2022, 5:42 PM
Do you get any error messages in the console? Have you added the domain you’re loading this from to CORS origins?
Jan 3, 2022, 5:42 PM
user S
the undefined reference error is the only console error, CORS is fine (no errors, localhost:3333 is added)
Jan 3, 2022, 5:51 PM
🤦 I should’ve seen this first:
window.onload=function(){
            let encodedQuery = encodeURIComponent('[_type == "senator"]');
                fetch(`<https://6dyl9k59.api.sanity.io/v2021-01-01/data/query/production?query=*${encodedQuery}>`)
                    .then(res => res.json())
                    .then(result => console.log(result)) // added result =>
            };

Jan 3, 2022, 5:55 PM
Your last then block doesn't have a parameter defined in the callback function.
Jan 3, 2022, 5:56 PM
Never mind. Knut beat me to it. 😁
Jan 3, 2022, 5:57 PM
ahhhh, thanks
user S
&amp;
user S
!!!!
Jan 3, 2022, 5:59 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?