Debugging Your API Calls - Next.js
1 let posts:any[] = [];
2
3 try {
4 const data = await fetch('https://api.vercel.app/blog');
5 posts = await data.json();
6
7 // Dump the response and data to the console
8 //console.log('Data:', posts); // Logs the parsed JSON data
9 console.dir(posts, { depth: null}); //Expand all nested properties
10 } catch (error2) {
11 console.error('Error fetching data:', error2);
12 }
13
14 return (
15 <>
16 <h2 className="w-full text-center text-xl">
17 Debugging Your API Calls - Next.js
18 </h2>
19 <ul>
20 {posts.map((post: any) => (
21 <li key={post.id}>· {post.title}</li>
22 ))}
23 </ul>
24 </>
25 )
26
Summary: The above fetch code calls the api.vercel.app/blog endpoint, then converts the response to json(). But what if nothing works? What if you get errors? What if the world runs out of mozzarella sticks tomorrow?!
Well that's where console.log() and console.dir() save the day.
I use console.log() for general logging purposes.
I use console.dir() for deeper inspection of objects (most JS array structures) or DOM elements.
Since this is a server component the output will get displayed to your server console (NOT your browser's console). You can place these commands along the way to trace out your expected output and troubleshoot the error of your ways.
A big help for your code, not so much for your mozzarella sticks.
Well that's where console.log() and console.dir() save the day.
I use console.log() for general logging purposes.
I use console.dir() for deeper inspection of objects (most JS array structures) or DOM elements.
Since this is a server component the output will get displayed to your server console (NOT your browser's console). You can place these commands along the way to trace out your expected output and troubleshoot the error of your ways.
A big help for your code, not so much for your mozzarella sticks.
... and just to show you that I'm not full of cheese here is the output to the API call:
- · Lorem Ipsum - What Is It and How to Use It?
- · The Benefits of Regular Exercise
- · Mastering the Art of Cooking
- · Traveling on a Budget - Tips and Tricks
- · The Rise of Artificial Intelligence in Modern Society
- · 10 Must-Read Books for Summer
- · The Importance of Mental Health Awareness
- · Exploring Ancient Ruins in South America
- · The Future of Space Exploration
- · Tips for Starting Your Own Business
- · Healthy Eating Habits for a Balanced Life
- · The History of Ancient Civilizations
- · Discovering Hidden Gems in Europe
- · The Power of Positive Thinking
- · The Evolution of Modern Art
- · Exploring National Parks in North America
- · The Science Behind Climate Change
- · Famous Landmarks Around the World
- · The Psychology of Happiness
- · Trends in Fashion for the New Season
- · The Benefits of Meditation for Stress Relief
- · A Guide to Starting Your Fitness Journey
- · The Impact of Social Media on Society
- · Culinary Delights from Around the World
- · Exploring Ancient Wonders of the World