import React, { useState, useEffect } from "react";
import "./style.css";
function App() {
const [movieData, setMovieData] = useState();
const [directorData, setDirectorData] = useState();
const [listData, setListData] = useState([]);
const submitHandler = () => {
setListData([
...listData,
{
movie: movieData,
director: directorData,
},
]);
setMovieData("");
setDirectorData("");
};
const removeHandler = (id) => {
const newlist = listData.filter((remId) => {
return remId !== id;
});
setListData(newlist)
};
return (
<div className="App">
<div>
<h1>Todo App</h1>
</div>
<div className="form">
<div>
<label>Movie</label>
<input
type="text"
placeholder="type items"
value={movieData}
onChange={(e) => setMovieData(e.target.value)}
/>
</div>
<div>
<label>Director</label>
<input
type="text"
placeholder="type items"
value={directorData}
onChange={(e) => setDirectorData(e.target.value)}
/>
</div>
<div>
<button onClick={submitHandler}>Submit</button>
</div>
</div>
<div>
{listData.map((item, index) => {
return (
<li key={index}>
<span>{item.movie}</span>, <span>{item.director}</span>{" "}
<span style={{ marginLeft: "2rem" }}>
<button onClick={removeHandler(index)} style={{ color: "red" }}>
X
</button>
</span>
</li>
);
})}
</div>
</div>
);
}
export default App;
As soon as I added removeHandler, I am getting too many re renders onSubmit. Its working fine once I remove removeHandler.
As soon as I added removeHandler, I am getting too many re renders onSubmit. Its working fine once I remove removeHandler. As soon as I added removeHandler, I am getting too many re renders onSubmit. Its working fine once I remove removeHandler.
CodePudding user response:
Change to onClick={() => removeHandler(index)}
and you also have to remove 'return' in your array.filter
remId !== id;
});
CodePudding user response:
This happens because you're not passing an arrow function to onClick.
You're writing onClick={removeHandler(index)}
instead of onClick={() => removeHandler(index)}
.
It's because functionName(param)
syntax is generally used to call functions so when you write that, it causes infinite renders.
CodePudding user response:
use this function some new changes
const removeHandler = (id) => { const newlist = [...listData]; newlist.splice(id, 1); setListData(newlist); };
and change onclick event
onClick={() => removeHandler(index)}