Its a program, which simply fetches a specific data, on every row by clicking "add record". I am having difficulty to execute delete button functionality , where on clicking it, that particular row will be deleted. Its should be implemented in DeleteHandler().
import React, { useState } from 'react'
const DataFetch = () => {
const [posts, setPosts] = useState([]);
const ClickHandler = () => {
const url = `https://swapi.dev/api/people/${Math.floor(Math.random() * 10) 1}`
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
setPosts([...posts,
json.name])
}
catch (error) {
console.log("error");
}
};
fetchData();
}
const DeleteHandler = (e) => {
const name = e.target.getAttribute("name")
console.log(name)
}
return (
<div>
<div>
<button onClick={ClickHandler}>ADD RECORD</button>
</div>
<table>
{posts.map((post) =>
<tr>
<td key={Math.random()}>{post}</td>
<td><button name={post} onClick={()=>DeleteHandler}>delete</button></td>
</tr>
)}
</table>
</div>
);
};
export default DataFetch
CodePudding user response:
Use this code
import React, { useState } from "react";
let uidArray = [];
const DataFetch = () => {
const [posts, setPosts] = useState([]);
const ClickHandler = () => {
const url = `https://swapi.dev/api/people/${
Math.floor(Math.random() * 10) 1
}`;
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
setPosts([...posts, json.name]);
} catch (error) {
console.log("error");
}
};
fetchData();
};
const DeleteHandler = (e) => {
const ele = document.getElementsByClassName(e)[0];
ele.remove();
};
return (
<div>
<div>
<button onClick={ClickHandler}>ADD RECORD</button>
</div>
<table>
{posts.map((post) => (
<tr className={post}>
<td key={Math.random()}>{post}</td>
<td>
<button name={post} onClick={() => DeleteHandler(post)}>
delete
</button>
</td>
</tr>
))}
</table>
</div>
);
};
export default DataFetch;
https://codesandbox.io/s/smoosh-breeze-rx7s0b
CodePudding user response:
Within your DeleteHandler() function you should just be able to call setPosts() and set the posts to itself minus the row that was clicked, and then your JSX will know to re render itself and the row should no longer be there.