0% found this document useful (0 votes)
6 views12 pages

Experiment 7 (FSD)

The document contains three React component implementations for fetching and displaying TODO items from an API. The first component retrieves TODOs by ID, the second submits a new post, and the third fetches TODOs by user ID, categorizing them into completed and uncompleted. Each component handles user input, API requests using Axios, and displays relevant messages or data based on the responses.

Uploaded by

vijaisreeragavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views12 pages

Experiment 7 (FSD)

The document contains three React component implementations for fetching and displaying TODO items from an API. The first component retrieves TODOs by ID, the second submits a new post, and the third fetches TODOs by user ID, categorizing them into completed and uncompleted. Each component handles user input, API requests using Axios, and displays relevant messages or data based on the responses.

Uploaded by

vijaisreeragavi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

61781922106041

AIM:

PROCEDURE:
61781922106041

1) import React from "react";

import axios from "axios";

class C2 extends React.Component {

constructor(props) {

super(props);

this.state = {

todos: [],

errorMessage: '',

inputId: ''

};

this.handleSubmit = this.handleSubmit.bind(this);

this.handleChange = this.handleChange.bind(this);

handleChange(event) {

this.setState({ inputId: event.target.value });

handleSubmit(event) {

event.preventDefault();

const { inputId } = this.state;

if (inputId.trim() === "") {

this.setState({ errorMessage: "Please enter a valid ID", todos: [] });

return;

axios.get(`https://jsonplaceholder.typicode.com/todos?id=${inputId}`)

.then(response => {
61781922106041

if (response.data.length > 0) {

this.setState({ todos: response.data, errorMessage: '' });

} else {

this.setState({ todos: [], errorMessage: "No TODO found for this ID" });

})

.catch(error => {

this.setState({ todos: [], errorMessage: "Error fetching data" });

console.error(error);

});

render() {

const { todos, errorMessage, inputId } = this.state;

return (

<div>

<form onSubmit={this.handleSubmit}>

<h1>Enter ID</h1>

<input

type="text"

name="inputId"

value={inputId}

onChange={this.handleChange}

/>

<br />

<button type="submit">Submit</button>

</form>
61781922106041

<div>

<h1>Todo List</h1>

todos.length > 0 &&

todos.map(todo => (

<div key={todo.id}>

<h2>Id: {todo.id}</h2>

<h2>User Id: {todo.userId}</h2>

<h2>Title: {todo.title}</h2>

<h2>Completed: {todo.completed ? "true" : "false"}</h2>

<hr />

</div>

))

errorMessage &&

<div style={{ color: "red" }}>

{errorMessage}

</div>

</div>

</div>

);

export default C2;


61781922106041

OUTPUT:
61781922106041

2) import React, { Component } from 'react'

import axios from 'axios'

class C1 extends React.Component {

constructor(props) {

super(props)

this.state = {

userId: '',

title: '',

body: '',

output: {}

this.handleSubmit=this.handleSubmit.bind(this)

this.handleChange=this.handleChange.bind(this)

handleChange(event) {

this.setState({[event.target.name]:event.target.value})

handleSubmit(event) {

event.preventDefault();

console.log(this.state);

axios.post('https://jsonplaceholder.typicode.com/posts',this.state)

.then(response=>

console.log("winner",response.data);

this.setState({output:response.data})

})

.catch(error=>console.log(error))
61781922106041

render() {

const {userId,title,body,output}=this.state

return (

<div>

<form onSubmit={this.handleSubmit}>

<h1> Enter User Id</h1>

<input type="text" name="userId" onChange={this.handleChange}/>

<br/>

<h1> Title </h1>

<input type="text" name="title" onChange={this.handleChange}/>

<br/>

<h1> Body</h1>

<input type="text" name="body"

onChange={this.handleChange} /> <br/>

<input type="submit"/> </form>

<p>Title : {output.title || null} </p>

<p> New id is {output.id || null}</p>

</div>

export default C1;

OUTPUT:
61781922106041

import React, { useState } from "react";

import axios from "axios";

const TodoFetcher = () => {

const [userId, setUserId] = useState("");

const [completedTodos, setCompletedTodos] = useState([]);

const [uncompletedTodos, setUncompletedTodos] = useState([]);

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

const fetchTodos = async () => {

if (!userId.trim()) {

setError("Please enter a valid userId.");

return;

try {

const response = await axios.get(

`https://jsonplaceholder.typicode.com/todos?userId=${userId}`

);

const todos = response.data;

const completed = todos.filter((todo) => todo.completed);

const uncompleted = todos.filter((todo) => !todo.completed);

setCompletedTodos(completed);

setUncompletedTodos(uncompleted);

setError("");
61781922106041

} catch (err) {

console.error(err);

setError("Failed to fetch todos.");

};

return (

<div style={{ padding: "20px", fontFamily: "Arial" }}>

<h2>Fetch Todos by User ID</h2>

<input

type="text"

value={userId}

placeholder="Enter userId"

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

/>

<button onClick={fetchTodos} style={{ marginLeft: "10px" }}>

Fetch Todos

</button>

{error && <p style={{ color: "red" }}>{error}</p>}

{completedTodos.length > 0 && (

<div>

<h3> Completed Todos</h3>

<table border="1" cellPadding="10">

<thead>

<tr>
61781922106041

<th>ID</th>

<th>Title</th>

<th>Completed</th>

</tr>

</thead>

<tbody>

{completedTodos.map((todo) => (

<tr key={todo.id}>

<td>{todo.id}</td>

<td>{todo.title}</td>

<td>{todo.completed.toString()}</td>

</tr>

))}

</tbody>

</table>

</div>

)}

{uncompletedTodos.length > 0 && (

<div style={{ marginTop: "20px" }}>

<h3> Uncompleted Todos</h3>

<table border="1" cellPadding="10">

<thead>

<tr>

<th>ID</th>

<th>Title</th>

<th>Completed</th>
61781922106041

</tr>

</thead>

<tbody>

{uncompletedTodos.map((todo) => (

<tr key={todo.id}>

<td>{todo.id}</td>

<td>{todo.title}</td>

<td>{todo.completed.toString()}</td>

</tr>

))}

</tbody>

</table>

</div>

)}

</div>

);

};
61781922106041

export default TodoFetcher;

RESULT:

You might also like