📄Assignments Of Class 17: Fetching Data from API in React

Rashmi Mishra
0

 ðŸ“„Assignments Of Class 17

Fetching Data from API in React


Assignment 1: Basic Fetch and Display

Task:
Write a React component to fetch data from https://jsonplaceholder.typicode.com/users and display the names in a list.

Solution:

import React, { useEffect, useState } from 'react'; 

function UserNames() {

  const [users, setUsers] = useState([]); 

  useEffect(() => {

    fetch('https://jsonplaceholder.typicode.com/users')

      .then(res => res.json())

      .then(data => setUsers(data))

      .catch(err => console.error(err));

  }, []); 

  return (

    <ul>

      {users.map(user => (

        <li key={user.id}>{user.name}</li>

      ))}

    </ul>

  );

} 

export default UserNames;


Assignment 2: Loading State Indicator

Task:
Add a loading message that appears while data is being fetched.

Solution:

import React, { useEffect, useState } from 'react'; 

function UserNames() {

  const [users, setUsers] = useState([]);

  const [loading, setLoading] = useState(true); 

  useEffect(() => {

    fetch('https://jsonplaceholder.typicode.com/users')

      .then(res => res.json())

      .then(data => {

        setUsers(data);

        setLoading(false);

      })

      .catch(err => {

        console.error(err);

        setLoading(false);

      });

  }, []); 

  if (loading) {

    return <p>Loading users...</p>;

  } 

  return (

    <ul>

      {users.map(user => (

        <li key={user.id}>{user.name}</li>

      ))}

    </ul>

  );

} 

export default UserNames;


Assignment 3: Display Name and Email

Task:
Modify the component to display both user name and email in the list.

Solution:

// Continue from Assignment 2

return (

  <ul>

    {users.map(user => (

      <li key={user.id}>

        {user.name} - {user.email}

      </li>

    ))}

  </ul>

);


Assignment 4: Error Handling Display

Task:
Show an error message if the fetch fails.

Solution:

import React, { useEffect, useState } from 'react'; 

function UserNames() {

  const [users, setUsers] = useState([]);

  const [loading, setLoading] = useState(true);

  const [error, setError] = useState(null); 

  useEffect(() => {

    fetch('https://jsonplaceholder.typicode.com/users')

      .then(res => {

        if (!res.ok) {

          throw new Error('Network response was not ok');

        }

        return res.json();

      })

      .then(data => {

        setUsers(data);

        setLoading(false);

      })

      .catch(err => {

        setError(err.message);

        setLoading(false);

      });

  }, []); 

  if (loading) return <p>Loading users...</p>;

  if (error) return <p>Error: {error}</p>;

   return (

    <ul>

      {users.map(user => (

        <li key={user.id}>{user.name} - {user.email}</li>

      ))}

    </ul>

  );

} 

export default UserNames;


Assignment 5: Fetch Data on Button Click

Task:
Create a button to fetch users only when clicked, instead of fetching on component load.

Solution:

import React, { useState } from 'react'; 

function FetchOnClick() {

  const [users, setUsers] = useState([]);

  const [loading, setLoading] = useState(false); 

  const fetchUsers = () => {

    setLoading(true);

    fetch('https://jsonplaceholder.typicode.com/users')

      .then(res => res.json())

      .then(data => {

        setUsers(data);

        setLoading(false);

      })

      .catch(() => setLoading(false));

  }; 

  return (

    <div>

      <button onClick={fetchUsers}>Fetch Users</button>

      {loading && <p>Loading...</p>}

      <ul>

        {users.map(user => (

          <li key={user.id}>{user.name} - {user.email}</li>

        ))}

      </ul>

    </div>

  );

} 

export default FetchOnClick;


Assignment 6: Display User Data in Cards (Basic Style)

Task:
Display each user in a card with name, email, and phone number.

Solution:

import React, { useEffect, useState } from 'react'; 

function UserCards() {

  const [users, setUsers] = useState([]);

  const [loading, setLoading] = useState(true); 

  useEffect(() => {

    fetch('https://jsonplaceholder.typicode.com/users')

      .then(res => res.json())

      .then(data => {

        setUsers(data);

        setLoading(false);

      })

      .catch(() => setLoading(false));

  }, []); 

  if (loading) return <p>Loading users...</p>; 

  return (

    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px' }}>

      {users.map(user => (

        <div

          key={user.id}

          style={{

            border: '1px solid #ccc',

            padding: '10px',

            borderRadius: '5px',

            width: '200px'

          }}

        >

          <h3>{user.name}</h3>

          <p><b>Email:</b> {user.email}</p>

          <p><b>Phone:</b> {user.phone}</p>

        </div>

      ))}

    </div>

  );

} 

export default UserCards;


Assignment 7: Add Search Filter to User List

Task:
Add a text input to filter users by name as the user types.

Solution:

import React, { useEffect, useState } from 'react'; 

function SearchableUserList() {

  const [users, setUsers] = useState([]);

  const [loading, setLoading] = useState(true);

  const [searchTerm, setSearchTerm] = useState('');

   useEffect(() => {

    fetch('https://jsonplaceholder.typicode.com/users')

      .then(res => res.json())

      .then(data => {

        setUsers(data);

        setLoading(false);

      });

  }, []);

 

  const filteredUsers = users.filter(user =>

    user.name.toLowerCase().includes(searchTerm.toLowerCase())

  );

 

  if (loading) return <p>Loading users...</p>;

 

  return (

    <div>

      <input

        type="text"

        placeholder="Search by name..."

        value={searchTerm}

        onChange={e => setSearchTerm(e.target.value)}

      />

      <ul>

        {filteredUsers.map(user => (

          <li key={user.id}>{user.name} - {user.email}</li>

        ))}

      </ul>

    </div>

  );

}

 

export default SearchableUserList;


Assignment 8: Display User Address in Card

Task:
Extend the card component to display user's full address (street, suite, city, zipcode).

Solution:

// Extending Assignment 6

<div key={user.id} style={{ ...cardStyle }}>

  <h3>{user.name}</h3>

  <p><b>Email:</b> {user.email}</p>

  <p><b>Phone:</b> {user.phone}</p>

  <p><b>Address:</b> {user.address.street}, {user.address.suite}, {user.address.city}, {user.address.zipcode}</p>

</div>


Assignment 9: Fetch Posts Instead of Users

Task:
Fetch data from https://jsonplaceholder.typicode.com/posts and display post titles.

Solution:

import React, { useEffect, useState } from 'react'; 

function PostList() {

  const [posts, setPosts] = useState([]);

  const [loading, setLoading] = useState(true);

 

  useEffect(() => {

    fetch('https://jsonplaceholder.typicode.com/posts')

      .then(res => res.json())

      .then(data => {

        setPosts(data);

        setLoading(false);

      });

  }, []);

 

  if (loading) return <p>Loading posts...</p>;

 

  return (

    <ul>

      {posts.map(post => (

        <li key={post.id}>{post.title}</li>

      ))}

    </ul>

  );

} 

export default PostList;


Assignment 10: Combine Loading, Error, and Data Display

Task:
Create a component that fetches users, handles loading and error states, and displays the data properly formatted.

Solution:

import React, { useEffect, useState } from 'react'; 

function UserData() {

  const [users, setUsers] = useState([]);

  const [loading, setLoading] = useState(true);

  const [error, setError] = useState(null);

 

  useEffect(() => {

    fetch('https://jsonplaceholder.typicode.com/users')

      .then(res => {

        if (!res.ok) throw new Error('Failed to fetch');

        return res.json();

      })

      .then(data => {

        setUsers(data);

        setLoading(false);

      })

      .catch(err => {

        setError(err.message);

        setLoading(false);

      });

  }, []);

 

  if (loading) return <p>Loading...</p>;

  if (error) return <p>Error: {error}</p>;

 

  return (

    <div>

      {users.map(user => (

        <div key={user.id} style={{ marginBottom: '10px' }}>

          <h4>{user.name}</h4>

          <p>Email: {user.email}</p>

          <p>Phone: {user.phone}</p>

        </div>

      ))}

    </div>

  );

}

 

export default UserData;


Summary:

These assignments cover:

  • Basic fetch usage
  • Managing loading and error states
  • Displaying data in lists and cards
  • Filtering data
  • Fetching different API endpoints
  • Handling user interaction (fetch on button click)

Post a Comment

0Comments

Post a Comment (0)