Lab 8
Lab 8
Lab 8
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
<ProductGet/>
<SendProducts/>
</React.StrictMode>
);
reportWebVitals();
ProductGets.js
import React, { Component } from 'react'
import axios from 'axios'
export default class ProductGet extends Component {
constructor(props) {
super(props)
this.state = {
posts:[],
errorMessage:' '
}
}
componentDidMount()
{
axios.get("https://jsonplaceholder.typicode.com/posts")
.then(response=>{
console.log(response)
this.setState({posts:response.data})
})
.catch(error=>{
console.log(error)
this.setState({errorMessage:' Error receiving Date'})
})
}
render() {
const { posts, errorMessage } = this.state
return (
<div><h1>List Prdoucts</h1>
{
posts.length ?
posts.map(post=><div key={post.id}>{post.title} <h1>{post.body}
</h1></div>):
null
}
{
}
</div>
)
}
}
SendProducts.js
import React, { Component } from 'react'
import axios from 'axios'
this.state = {
userId:'',
title:'',
body:'',
res:[]
}
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(response.data);
this.setState({res:response.data})
}
)
.catch(error=>console.log(error))
}
render() {
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>
</div>
)
}
}
Output :