Practice: Build a Simple App with Async Data Fetching

1. Welcome and Icebreaker:

  • If you could build any app that fetches live data, what would it do?

2. Outline the Session:

  • We’ll practice building a simple TypeScript app that fetches data asynchronously.
  • Learning Outcomes: Apply async/await, Promises, and error handling to a real-world scenario.
  • Let’s build something useful!

3. Concept Explanation:

  • Building a small app helps you practice async programming and API interaction.
  • We’ll use fetch to get data from a public API and display it.
  • Handle loading, success, and error states.

4. Live Coding Demonstration:

async function fetchPosts() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts?_limit=5');
    if (!response.ok) throw new Error('Network error');
    const posts = await response.json();
    console.log('Posts:', posts);
  } catch (error) {
    console.error('Failed to fetch posts:', error);
  }
}

fetchPosts();

5. Tasks:

  • Short Exercise:
    1. Build a function that fetches and prints a list of users from a public API.
    2. Add error handling for failed requests.
    3. Extend your app to fetch and display details for a single user.