I'm trying to create small app based on Json server package which will help me to remember movies I want to watch when I have free time, want to learn React and Axios so I'm doing it with these technologies , Idea is when I click on add movie button - movie will be added to Json database,
when click on delete - particular movie will be deleted
and when click on the list - I will be able to edit text,
Delete works if I do something like http://localhost:3000/movies/1, to show what id should it delete, but is there any way to set it? To delete the list connected to button I'm clicking at? something like http://localhost:3000/movies/"id"? I will be grateful for any help as I totally don't have any idea how to move on with it
import React from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
import List from "./list.jsx";
class Form extends React.Component {
constructor(props) {
super(props)
this.state = {
name:'',
type:'',
description:'',
id:'',
movies: [],
}
}
handleChangeOne = e => {
this.setState({
name:e.target.value
})
}
handleChangeTwo = e => {
this.setState({
type:e.target.value
})
}
handleChangeThree = e => {
this.setState({
description:e.target.value
})
}
handleSubmit = e => {
e.preventDefault()
const url = `http://localhost:3000/movies/`;
axios.post(url, {
name: this.state.name,
type: this.state.type,
description:this.state.description,
id:this.state.id
})
.then(res => {
// console.log(res);
// console.log(res.data);
this.setState({
movies:[this.state.name,this.state.type,this.state.description, this.state.id]
})
})
}
handleRemove = (e) => {
const id = this.state.id;
const url = `http://localhost:3000/movies/`;
// const id = document.querySelectorAll("li").props['data-id'];
e.preventDefault();
axios.delete(url + id)
.then(res => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
})
}
// editMovie = e => {
// const url = `http://localhost:3000/movies/`;
// e.preventDefault();
// const id = e.target.data("id");
// axios.put(url + id, {
// name: this.state.name,
// type: this.state.type,
// description:this.state.description,
// })
// .then(res => {
// console.log(res.data);
// })
// .catch((err) => {
// console.log(err);
// })
// }
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="movie" onChange={this.handleChangeOne}/>
<input type="text" placeholder="type of movie" onChange={this.handleChangeTwo}/>
<textarea cols={40} rows={5} placeholder="description of the movie" onChange={this.handleChangeThree}></textarea>
<input type="submit" value="Add movie"></input>
<List removeClick={this.handleRemove} editClick={this.editMovie}/>
</form>
)
}
}
export default Form
List:
import React from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
class List extends React.Component{
constructor(props){
super(props)
this.state = {
movies: [],
}
}
componentDidMount() {
const url = `http://localhost:3000/movies`;
console.log(url);
axios.get(url)
.then(res => {
console.log(res.data);
const movies = res.data;
this.setState({
movies: movies
})
})
.catch((err) => {
console.log(err);
})
}
// editMovie =(e) => {
// console.log("it works with edit!");
// if (typeof this.props.editClick === "function") {
// this.props.editClick(e)
// } else {
// console.log("Doesn't work with edit");
// }
// }
removeMovie =(e) => {
console.log("it works with remove!");
if (typeof this.props.removeClick === "function") {
this.props.removeClick(e)
} else {
console.log("Doesn't work with remove");
}
}
render(){
let movies = this.state.movies.map(e =>
<ul onClick={this.editMovie}>
<li data-id={e.id}>
{e.name}
</li>
<li data-id={e.id}>
{e.type}
</li>
<li data-id={e.id}>
{e.description}
</li>
<button type="submit" onClick={this.removeMovie}>Delete</button>
</ul>)
return(
<div>
{movies}
</div>
)
}
}
export default List;
Json part
{
"movies": [
{
"id": 1,
"name": "Kongi",
"type": "drama",
"description": "movie about monkey"
},
{
"id": 2,
"name": "Silent Hill",
"type": "thriller",
"description": "movie about monsters"
},
{
"name": "Harry potter",
"type": "fantasy",
"description": "movie about magic and glory",
"id": 3
}
]
}
You could pass the movie object to the removeMovie function in your List component and pass that to the this.props.removeClick function. You could then take the id of the movie to use for your request, and remove the movie from state if the DELETE request is successful.
Example
class Form extends React.Component {
handleRemove = movie => {
const url = `http://localhost:3000/movies/${movie.id}`;
axios
.delete(url)
.then(res => {
this.setState(previousState => {
return {
movies: previousState.movies.filter(m => m.id !== movie.id)
};
});
})
.catch(err => {
console.log(err);
});
};
// ...
}
class List extends React.Component {
removeMovie = (e, movie) => {
e.preventDefault();
if (this.props.removeClick) {
this.props.removeClick(movie);
}
};
// ...
render() {
return (
<div>
{this.state.movies.map(movie => (
<ul onClick={this.editMovie}>
<li data-id={movie.id}>{movie.name}</li>
<li data-id={movie.id}>{movie.type}</li>
<li data-id={movie.id}>{movie.description}</li>
<button type="submit" onClick={e => this.removeMovie(e, movie)}>
Delete
</button>
</ul>
))}
</div>
);
}
}
An simple example using hooks:
const URL = 'https://jsonplaceholder.typicode.com/users'
const Table = () => {
const [employees, setEmployees] = React.useState([])
React.useEffect(() => {
getData()
}, [])
const getData = async () => {
const response = await axios.get(URL)
setEmployees(response.data)
}
const removeData = (id) => {
axios.delete(`${URL}/${id}`).then(res => {
const del = employees.filter(employee => id !== employee.id)
setEmployees(del)
})
}
const renderHeader = () => {
let headerElement = ['id', 'name', 'email', 'phone', 'operation']
return headerElement.map((key, index) => {
return <th key={index}>{key.toUpperCase()}</th>
})
}
const renderBody = () => {
return employees && employees.map(({ id, name, email, phone }) => {
return (
<tr key={id}>
<td>{id}</td>
<td>{name}</td>
<td>{email}</td>
<td>{phone}</td>
<td className='opration'>
<button className='button' onClick={() => removeData(id)}>Delete</button>
</td>
</tr>
)
})
}
return (
<>
<h1 id='title'>React Table</h1>
<table id='employee'>
<thead>
<tr>{renderHeader()}</tr>
</thead>
<tbody>
{renderBody()}
</tbody>
</table>
</>
)
}
ReactDOM.render(<Table />, document.getElementById('root'));
Related
Been trying to figure this out for a couple hours now but I'm stumped. According to the console, when I make a patch request, the request goes through and actually updates the information, but my map function is breaking after that and it renders a blank page.
Here's the component with the error:
import { useState, useEffect } from "react"
// import { EmployeeForm } from "./EmployeeForm"
export function EmployeeTable() {
const [employees, setEmployees] = useState([])
const [employeeId, setEmployeeId] = useState([])
const [update, setUpdate] = useState(false)
const [firstName, setFirstName] = useState('')
const [lastName, setLastName] = useState('')
useEffect(() => {
fetch('/api/employees')
.then(res => res.json())
.then(json => setEmployees(json.employees)
)
}, [])
const updateEmployee = async () => {
try {
const res = await fetch(`/api/employees/${employeeId}`,
{method: 'PATCH', body: JSON.stringify({firstName, lastName})})
const json = await res.json()
const employeesCopy = [...employees]
const index = employees.findIndex((employee) => employee.id === employeeId)
employeesCopy[index] = json.employee
setEmployees(employeesCopy)
setFirstName('')
setLastName('')
setUpdate(false)
setEmployeeId([])
} catch (err) {
console.log(err)
}
}
const submitForm = async (event) => {
event.preventDefault()
if(update){
updateEmployee()
}
}
const deleteEmployee = async (id) => {
try {
await fetch(`/api/employees/${id}`, {method: 'DELETE'})
setEmployees(employees.filter(employee => employee.id !== id))
} catch (error) {
}
}
const setEmployeeToUpdate = (id) => {
const employee = employees.find(emp => emp.id === id)
if(!employee) return
setUpdate(true)
setEmployeeId(employee.id)
setFirstName(employee.firstName)
setLastName(employee.lastName)
}
return (
<div>
<header>
<h1>Employees</h1>
</header>
{employees.length > 0 ? (
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{employees.map(({id, firstName, lastName}) => {
return(
<tr key={id}>
<td>{firstName}</td>
<td>{lastName}</td>
<td>
<button onClick={() => setEmployeeToUpdate(id)}>UPDATE</button>
<button onClick={() => deleteEmployee(id)}>DELETE</button>
</td>
</tr>
)
})}
</tbody>
</table>
) : (
// If for some reason the employees cannot be returned the page will render this p tag.
<p>No employees</p>
)}
<form onSubmit={submitForm}>
<div>
<div>
<input type="text" value={firstName} onChange={e => setFirstName(e.target.value)}/>
</div>
<div>
<input type="text" value={lastName} onChange={e => setLastName(e.target.value)}/>
</div>
<div>
<button type='submit'>{update ? 'Update' : 'Create'}</button>
</div>
</div>
</form>
</div>
)
}
And here is the MirageJS server.js
import { createServer, Model } from "miragejs";
import faker from "faker";
import avatar from "./avatar.png";
export function makeServer({ environment = "test" } = {}) {
let server = createServer({
environment,
models: {
employee: Model,
},
seeds(server) {
for (let i = 0; i < 10; i++) {
server.create("employee", {
id: faker.datatype.uuid(),
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
email: faker.internet.email(),
phone: faker.phone.phoneNumber(),
bio: faker.lorem.paragraph(),
avatar: avatar,
address: {
streetAddress: `${faker.address.streetAddress()} ${faker.address.streetName()}`,
city: faker.address.city(),
state: faker.address.stateAbbr(),
zipCode: faker.address.zipCode(),
},
});
}
},
routes() {
this.namespace = "api";
this.get(
"/employees",
(schema) => {
return schema.employees.all();
},
{ timing: 1000 }
);
this.patch(
"/employees/:id",
(schema, request) => {
const attrs = JSON.parse(request.requestBody);
const employee = schema.employees.find(request.params.id);
employee.update(attrs);
},
{ timing: 300 }
);
this.delete(
"/employees/:id",
(schema, request) => {
const employee = schema.employees.find(request.params.id);
employee.destroy();
return new Response();
},
{ timing: 300 }
);
},
});
return server;
}
Provide a default value, to destructure from employees.map(({id, firstName, lastName}).
{employees.filter(item => item).map(({ id = 0, firstName = 'empty', lastName = 'empty' }) => {...
setEmployees((prevState) => {
const index = prevState.findIndex((employee) => employee.id === employeeId);
let newEmployees = […prevState];
newEmployees[index] = json.employee;
return newEmployees;
}))
You miss return in server.js patch request.
server.js
this.patch(
"/employees/:id",
(schema, request) => {
const attrs = JSON.parse(request.requestBody);
const employee = schema.employees.find(request.params.id);
return employee.update(attrs);
},
{ timing: 300 }
);
I have two pages on my react app. One page allows you to submit a post, and the second page shows all of the posts. I need to be able to retrieve the data from the state on one page, but I am receiving an error. What am I doing wrong to display this, because I thought I could use props to gather the state from my post page.
My Display Post Page:
import React from 'react';
import './App.css';
export default class Scroll extends React.Component {
render() {
return (
<div className="flex-container">
<div className="post">
{this.props.displayPost(this.props.state.posts)}
</div>
</div>
);
}
}
My post page:
import React from 'react';
import axios from 'axios';
import './App.css';
import { post } from '../../routes/routes';
export default class PersonList extends React.Component {
state = {
title: "",
body: "",
posts: []
};
componentDidMount = () => {
this.getPost();
}
getPost = () => {
axios.get("http://localhost:5000/posts/save")
.then((response) => {
const data = response.data;
this.setState({ posts: data });
console.log("Data has been recieved")
})
.catch(() => {
alert("Error recieving data")
})
}
handleChange = (event) => {
const target = event.target;
const name = target.name;
const value = target.value;
this.setState({
[name]: value
})
};
submit = (event) => {
event.preventDefault();
const payload = {
title: this.state.title,
body: this.state.body,
}
axios({
url: 'http://localhost:5000/posts/save',
method: 'POST',
data: payload,
})
.then(() => {
console.log('Data sent to the server');
})
.catch(() => {
console.log('Internal server error');
});
};
displayPost = (posts) => {
if (!post.length) return null;
return posts.map((post, index) => {
<div key={index}>
<h3 id="post-text">{post.title}</h3>
<p id="post-text">{post.body}</p>
</div>
});
}
render() {
console.log("State ", this.state)
return (
<div className="flex-container-home">
<div className="app">
<form onSubmit={this.submit}>
<input
placeholder="title"
type="text"
name="title"
value={this.state.title}
onChange={this.handleChange}
/>
<textarea placeholder="description"
name="body"
cols="30" rows="10"
value={this.state.body}
onChange={this.handleChange}
>
</textarea>
<button>Submit</button>
</form>
</div>
</div>
)
}
}
Here is working example:
import React from "react";
export default class PersonList extends React.Component {
state = {
title: "",
body: "",
posts: [],
};
componentDidMount = () => {
this.getPost();
};
getPost = () => {
this.setState({ posts: ["post1", "post2", "post3"] });
};
displayPost = (posts) => {
if (!posts || !posts.length) return null;
return posts.map((post, index) => (
<div key={index}>
<p>{post}</p>
</div>
));
};
render() {
return (
<div className="App">
<Scroll displayPost={this.displayPost} posts={this.state.posts} />
</div>
);
}
}
class Scroll extends React.Component {
render() {
return (
<div className="post">
Posts: {this.props.displayPost(this.props.posts)}
</div>
);
}
}
I asked similar question earlier, but didn't get much back. I have two modals for user auth: join and login. Each modal has a link to the other one. Displayed login errors persist when you click on the "sign up" and switch to the join modal and vise versa. I tried to set the state.errors to empty array, but the errors still persist. I changed handleSwitch to callback. The errors array still has length. I tried using switched as part of the state, resetting it to true in handleSwitch and ternary, no result either. Can anybody suggest an alternative solution.
import React from 'react';
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
errors: [],
switched: false
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleSwitch = this.handleSwitch.bind(this);
this.mapErrors = this.mapErrors.bind(this);
this.handleErrors = this.handleErrors.bind(this);
}
componentDidMount() {
this.setState({ errors: this.props.errors})
}
componentDidUpdate(prev) {
if (prev.errors.length !== this.props.errors.length) {
this.setState( {errors: this.props.errors} )
}
}
handleInput(type) {
return (err) => {
this.setState({ [type]: err.currentTarget.value })
};
}
handleSubmit(event) {
event.preventDefault();
const user = Object.assign({}, this.state);
this.props.processForm(user)
// .then(() => this.props.history.push('/users')); //change to /videos later
}
handleSwitch() {
// debugger
this.setState({ errors: [] }, function () {
this.props.openModal('signup')
});
// debugger
}
mapErrors() {
if (this.state.errors.length) {
return this.state.errors.map((error, i) => {
return <p key={i}>{error}</p>
})
}
}
handleErrors() {
debugger
if (!this.state.switched) {
return <div className="errors">{this.mapErrors}</div>
} else {
return null;
}
};
render() {
console.log(this.state.errors)
return (
<div className="login-form">
<div>
<h2 className="login-header">Log in to Foxeo</h2>
</div>
<form>
<input className="login-email"
type="text"
value={this.state.email}
placeholder="Email address"
onChange={this.handleInput('email')}
/>
<input className="login-password"
type="password"
value={this.state.password}
placeholder="Password"
onChange={this.handleInput('password')}
/>
<div className="errors">{this.mapErrors()}</div>
{/* { this.state.switched ?
<div className="errors">{this.handleErrors()}</div> :
<div className="errors">{this.mapErrors()}</div>
} */}
<button className="login-button" onClick={this.handleSubmit}>Log in with email</button>
<div className="login-footer">Don't have an account?
{/* <button className="login-form-btn" onClick={() => this.props.openModal('signup')}>Join</button> */}
<button className="login-form-btn" onClick={ this.handleSwitch}> Join</button>
</div>
</form>
</div>
);
}
};
export default Login;
I suggest getting the new errors from the props instead of from state:
mapErrors() {
if (this.props.errors.length) {
return this.props.errors.map((error, i) => {
return <p key={i}>{error}</p>
})
Dispatching resetErrors action solved the issue. The handleSwitch method is quite simple:
handleSwitch() {
this.props.resetErrors()
this.props.openModal('signup')
}
session actions:
import * as apiUtil from '../util/session_api_util';
export const RECEIVE_CURRENT_USER = 'RECEIVE_CURRENT_USER';
export const LOGOUT_CURRENT_USER = 'LOGOUT_CURRENT_USER';
export const RECEIVE_ERRORS = 'RECEIVE_ERRORS';
export const CLEAR_ERRORS = 'CLEAR_ERRORS';
const receiveErrors = (errors) => ({
type: RECEIVE_ERRORS,
errors
})
const clearErrors = () => ({
type: CLEAR_ERRORS,
errors: []
})
const receiveCurrentUser = (user) => ({
type: RECEIVE_CURRENT_USER,
user
});
const logoutCurrentUser = () => ({
type: LOGOUT_CURRENT_USER
});
export const signup = user => dispatch => (
apiUtil.signup(user).then(user => (
dispatch(receiveCurrentUser(user))
), err => (
dispatch(receiveErrors(err.responseJSON))
))
);
export const login = user => dispatch => {
return apiUtil.login(user).then(user => {
dispatch(receiveCurrentUser(user))
}, err => (
dispatch(receiveErrors(err.responseJSON))
))
};
export const logout = () => dispatch => apiUtil.logout()
.then(() => dispatch(logoutCurrentUser()));
export const resetErrors = () => dispatch(clearErrors());
session errors reducer:
import { RECEIVE_ERRORS, RECEIVE_CURRENT_USER, CLEAR_ERRORS } from '../actions/session_actions';
const sessionErrorsReducer = (state = [], action) => {
Object.freeze(state);
switch (action.type) {
case RECEIVE_ERRORS:
return action.errors;
case CLEAR_ERRORS:
return [];
case RECEIVE_CURRENT_USER:
return [];
default:
return state;
}
};
export default sessionErrorsReducer;
I am trying to make live search for name in table but i can't make live search i don't know how to do this i wrote my code like this as i mentioned please help me how to make live search on name field foe table and in Search Page i used onSubmit={this.props.loaddata like this thanks
import React, { Component } from "react";
import Search from "../../views/Cars/Search";
class Search1 extends Component {
constructor(props) {
super(props);
this.state = {
query: []
};
}
// Get Data from filter date
getData = async e => {
try {
const search = e.target.elements.search.value;
e.preventDefault();
const res = await fetch(`https://swapi.co/api/people/?search=${search}`);
const query = await res.json();
console.log(query);
this.setState({
query: query.results
});
} catch (e) {
console.log(e);
}
};
async componentDidMount() {
// let authToken = localStorage.getItem("Token");
try {
const res = await fetch(`https://swapi.co/api/people/`);
const query = await res.json();
// console.log(movie);
this.setState({
query: query.results
});
} catch (e) {
console.log(e);
}
}
render() {
const options = this.state.query.map(r => <li key={r.id}>{r.name}</li>);
return (
<div>
<Search loaddata={this.getData} />
{options}
</div>
);
}
}
export default Search1;
Genrally You can try React-Search
import Search from 'react-search'
import ReactDOM from 'react-dom'
import React, { Component, PropTypes } from 'react'
class TestComponent extends Component {
HiItems(items) {
console.log(items)
}
render () {
let items = [
{ id: 0, value: 'ruby' },
{ id: 1, value: 'javascript' },
{ id: 2, value: 'lua' },
{ id: 3, value: 'go' },
{ id: 4, value: 'julia' }
]
return (
<div>
<Search items={items} />
<Search items={items}
placeholder='Pick your language'
maxSelected={3}
multiple={true}
onItemsChanged={this.HiItems.bind(this)} />
</div>
)
}
}
Made few changes to your component. Send e.target.value from your child component
class Search1 extends Component {
constructor(props) {
super(props);
this.state = {
query: []
};
}
// Get Data from filter date
getData = search => {
const url = `https://swapi.co/api/people${search ? `/?search=${search}` : ``}`;
// e.preventDefault();
fetch(url)
.then(res => res.json())
.then(data =>
this.setState({
query: data.results || []
})).catch(e => console.log(e));
};
async componentDidMount() {
// let authToken = localStorage.getItem("Token");
this.getData();
}
render() {
const options = this.state.query.map(r => <li key={r.id}>{r.name}</li>);
return (
<div>
<Search loaddata={this.getData} />
{options}
</div>
);
}
}
export default Search1;
For Gettind Data from Api you can follow this code of react-search
import Search from 'react-search'
import ReactDOM from 'react-dom'
import React, { Component, PropTypes } from 'react'
class TestComponent extends Component {
constructor (props) {
super(props)
this.state = { repos: [] }
}
getItemsAsync(searchValue, cb) {
let url = `https://api.github.com/search/repositories?q=${searchValue}&language=javascript`
fetch(url).then( (response) => {
return response.json();
}).then((results) => {
if(results.items != undefined){
let items = results.items.map( (res, i) => { return { id: i, value: res.full_name } })
this.setState({ repos: items })
cb(searchValue)
}
});
}
render () {
return (
<div>
<Search items={this.state.repos}
multiple={true}
getItemsAsync={this.getItemsAsync.bind(this)}
onItemsChanged={this.HiItems.bind(this)} />
</div>
)
}
fetching data from API and display it but I want display the information of corresponding selected data using radio button but not able to display the data when selecting radio button
if condition is not working in handleData()
so any one tell where I'm doing wrong
import React, {component, useStates} from 'react';
import axios from 'axios';
export default class Posts extends React.Component {
constructor(){
super();
this.handleData = this.handleData.bind(this);
this. state = {
details: [],
selected: [],
hndleres:[]
}
}
// pagination
componentDidMount() {
this.renderData();
this.displyhandleData();
}
renderData(){
axios.get(`https://jsonplaceholder.typicode.com/posts`)
.then(res => {
const details = res.data;
this.setState({ details });
})
}
renderList(){
return(this.state.details).map((data, index) =>{
const uID = data.userId
const ID = data.id
const Body =data.body
const Title = data.title
return(
<tr>
<td><input type="radio" name="details" value={ID} onChange={this.handleData}></input></td>
<td>{ID}</td>
<td>{uID}</td>
<td>{Title}</td>
<td>{Body}</td>
</tr>
)
} )
}
handleData = (e) => {
this.state.value = e.target.value;
//debugger;
console.log(e.target.value)
debugger;
if(e.target.value != '1')
{
debugger;
let url = 'https://jsonplaceholder.typicode.com/posts'
const data = { "ID": e.target.value }
const res= axios.get(url, data)
.then(res =>{
this.setState = ({ hndleres : res.data})
});
}
else{
this.displyhandleData();
}
}
displyhandleData(){
return(this.state.hndleres).map((datas,index) =>{
const uID = datas.userId
const ID = datas.id
const Body =datas.body
const Title = datas.title
return(
<tr>
<td><input type="radio" name="details" value={ID} onChange={this.handleData}></input></td>
<td>{ID}</td>
<td>{uID}</td>
<td>{Title}</td>
<td>{Body}</td>
</tr>
)
})
}
render() {
return (
<div>
<table className="table">
{ this.renderList()}
</table>
<table className="table">
{ this.displyhandleData()}
</table>
</div>
)
}
}
so any one tell me where I'm doing wrong
render data from api but not display data of selected radio button:
There are multiple issues in your code, like mutating state directly, passing params obj in axios, And overriding this.setState function instead of calling it. I have corrected a few. Have a look and let me know if this helps
import React from "react";
import axios from "axios";
export default class Posts extends React.Component {
constructor() {
super();
this.handleData = this.handleData.bind(this);
this.state = {
details: [],
selected: [],
hndleres: []
};
}
// pagination
componentDidMount() {
this.renderData();
this.displyhandleData();
}
renderData() {
axios.get(`https://jsonplaceholder.typicode.com/posts`).then(res => {
const details = res.data;
this.setState({ details });
});
}
renderList() {
return this.state.details.map((data, index) => {
const uID = data.userId;
const ID = data.id;
const Body = data.body;
const Title = data.title;
return (
<tr>
<td>
<input
type="radio"
name="details"
value={ID}
onChange={this.handleData}
></input>
</td>
<td>{ID}</td>
<td>{uID}</td>
<td>{Title}</td>
<td>{Body}</td>
</tr>
);
});
}
handleData = e => {
//debugger;
console.log(e.target.value);
debugger;
if (e.target.value != "1") {
debugger;
let url = "https://jsonplaceholder.typicode.com/posts";
const data = { userId: e.target.value };
axios.get(url, { params: data }).then(res => {
this.setState({ hndleres: res.data });
});
} else {
this.displyhandleData();
}
};
displyhandleData() {
return this.state.hndleres.map((datas, index) => {
const uID = datas.userId;
const ID = datas.id;
const Body = datas.body;
const Title = datas.title;
return (
<tr>
<td>
<input
type="radio"
name="details"
value={ID}
onChange={this.handleData}
></input>
</td>
<td>{ID}</td>
<td>{uID}</td>
<td>{Title}</td>
<td>{Body}</td>
</tr>
);
});
}
render() {
return (
<div>
<table className="table">{this.renderList()}</table>
<table className="table">{this.displyhandleData()}</table>
</div>
);
}
}