Assignments Of Day 10: Component Lifecycle (Class Components)
Assignment 1: Fetching Data from an API Using componentDidMount
Objective:
Create a class component that fetches data from a mock API (use https://jsonplaceholder.typicode.com/posts) and displays a list of posts. The API data should be fetched using the componentDidMount lifecycle method.
Steps:
1. Set up the basic component: Create a class component named Posts.
2. Initialize the state: Add a state property to store the fetched data and any loading status.
3. Use componentDidMount: Use componentDidMount to fetch data when the component is mounted.
4. Display the data: Once the data is fetched, display the list of posts.
Solution:
Step 1: Set up the basic component
Start by creating the Posts component class.
jsx
Copy code
import React from 'react';
class Posts extends React.Component {
// Step 2: Initialize the state to store data and loading status
constructor(props) {
super(props);
this.state = {
posts: [], // To store the fetched posts
loading: true // To indicate loading state
};
}
// Step 3: Use componentDidMount to fetch data
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json()) // Parse the response as JSON
.then(data => {
this.setState({ posts: data, loading: false }); // Set state with the fetched data and set loading to false
})
.catch(error => console.log('Error fetching data:', error)); // Handle errors
}
// Step 4: Display the data
render() {
const { posts, loading } = this.state;
// Display loading message until the data is fetched
if (loading) {
return <div>Loading...</div>;
}
// Once data is loaded, display the posts
return (
<div>
<h1>List of Posts</h1>
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
}
export default Posts;
Explanation:
1. State Initialization: The component has a posts array to store the fetched data, and a loading boolean to show a loading message until the data is available.
2. Fetching Data with componentDidMount:
o componentDidMount is called once the component is mounted in the DOM. This is where we want to trigger the API request to fetch data.
o The fetch function makes a request to the URL 'https://jsonplaceholder.typicode.com/posts' to retrieve a list of posts. We then parse the response to JSON and update the state with the fetched data.
o If an error occurs during the fetch, it is logged in the console.
3. Rendering the Data:
o In the render method, we check if the loading state is true. If so, we show a "Loading..." message.
o Once the loading state is set to false (indicating that the data is loaded), we display the list of posts using the map function to iterate over the posts array and render each post's title.
Expected Output:
- Initially, the page will show "Loading...".
- After the data is fetched, it will display the list of posts with their titles.
Assignment 2: Timer Component Using componentDidMount and componentWillUnmount
Objective:
Create a timer component that counts seconds from 0 when mounted. Ensure the timer is cleared using componentWillUnmount to prevent it from running after the component is unmounted.
Steps:
1. Set up the basic component: Create a class component named Timer.
2. Initialize the state: Add a state property to track the time.
3. Start the timer in componentDidMount: Set up a timer using setInterval.
4. Clear the timer in componentWillUnmount: Clean up the timer to avoid memory leaks when the component is removed.
5. Display the timer: Render the current time.
Solution:
Step 1: Set up the basic component
Create the Timer component class.
jsx
Copy code
import React from 'react';
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
time: 0 // To store the current time
};
this.timerID = null; // To store the timer ID for clearing
}
// Step 3: Start the timer in componentDidMount
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000); // Set an interval to update time every second
}
// Step 4: Clear the timer in componentWillUnmount
componentWillUnmount() {
clearInterval(this.timerID); // Clean up the timer when the component unmounts
}
// Method to update the time
tick() {
this.setState(prevState => ({
time: prevState.time + 1
}));
}
// Step 5: Display the timer
render() {
return <h1>Time: {this.state.time}s</h1>;
}
}
export default Timer;
Explanation:
1. State Initialization:
o The state has a time property that starts at 0 to track the number of seconds.
o The timerID is initialized as null and will later hold the ID of the timer so that it can be cleared.
2. Starting the Timer (componentDidMount):
o Inside componentDidMount, we set up a timer using setInterval, which calls the tick method every second (1000 milliseconds).
o The tick method increments the time state by 1 every time it’s called.
3. Clearing the Timer (componentWillUnmount):
o When the component is about to be removed from the DOM (i.e., unmounted), the componentWillUnmount method is called. Here, we clear the interval using clearInterval(this.timerID) to stop the timer and avoid memory leaks.
4. Rendering the Timer:
o The render method displays the current time in seconds, which updates every second as the time state changes.
Expected Output:
- The page will initially show "Time: 0s".
- After one second, it will update to "Time: 1s", and this will continue to increment every second.
- If the component is unmounted, the timer will stop.
Assignment 3: Cleanup Example (Removing Event Listeners)
Objective:
Create a component that sets up an event listener when mounted (e.g., listening for mouse movements) and removes the listener when the component is unmounted.
Steps:
1. Set up the basic component: Create a class component named MouseTracker.
2. Add an event listener in componentDidMount: Set up an event listener for mouse movements.
3. Remove the event listener in componentWillUnmount: Clean up the event listener to prevent memory leaks.
Solution:
Step 1: Set up the basic component
Create the MouseTracker component class.
jsx
Copy code
import React from 'react';
class MouseTracker extends React.Component {
constructor(props) {
super(props);
this.state = {
x: 0, // Mouse x-coordinate
y: 0 // Mouse y-coordinate
};
}
// Step 2: Add the event listener in componentDidMount
componentDidMount() {
window.addEventListener('mousemove', this.handleMouseMove);
}
// Step 3: Remove the event listener in componentWillUnmount
componentWillUnmount() {
window.removeEventListener('mousemove', this.handleMouseMove);
}
// Method to update the mouse coordinates
handleMouseMove = (event) => {
this.setState({
x: event.clientX,
y: event.clientY
});
}
// Step 4: Display the mouse coordinates
render() {
return (
<div>
<h1>Move your mouse!</h1>
<p>Mouse Position: ({this.state.x}, {this.state.y})</p>
</div>
);
}
}
export default MouseTracker;
Explanation:
1. State Initialization:
o The component has two state variables, x and y, to store the mouse's position on the screen.
2. Adding the Event Listener (componentDidMount):
o The componentDidMount method adds an event listener to the window for the mousemove event. When the mouse is moved, the handleMouseMove method is called.
3. Removing the Event Listener (componentWillUnmount):
o The componentWillUnmount method is called just before the component is removed from the DOM. Here, we remove the event listener to prevent memory leaks when the component is no longer in use.
4. Rendering the Mouse Coordinates:
o The render method displays the mouse's current coordinates, which update as the mouse moves.
Expected Output:
- As you move the mouse, the coordinates will be displayed and updated in real-time.
- If the component is unmounted (e.g., if you navigate away from the page), the event listener will be removed.
Conclusion:
These assignments cover common lifecycle methods such as componentDidMount, componentWillUnmount, and managing state in React class components. Understanding these methods and their applications is essential for working with side effects like data fetching, event handling, and cleaning up resources.
