Lab 8

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Program :

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';

import ProductGet from './ProductGet';


import SendProducts from './SendProducts';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<React.StrictMode>

<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

}
{

errorMessage? <div> {errorMessage}</div>:null

}
</div>
)
}
}
SendProducts.js
import React, { Component } from 'react'
import axios from 'axios'

export default class SendProducts extends Component {


constructor(props) {
super(props)

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 :

Getting all the 200 products


Getting details from the users and sending post request to the server

You might also like