When i press my fetchApi
button, a new address appears, and if i keep pressing, it keeps adding more address, but when i press the removeElement
button, it deletes all the addresses, how can i make it so it only removes the one im pressing?
const removeElement = (index) => {
const newData = [];
setAllData(newData);
};
const fetchApi = async () => {
try {
setLoading(true);
await axios
.get("https://random-data-api.com/api/v2/addresses")
.then((response) => {
setAllData([...allData, response.data]);
console.log(response.data);
});
} catch (error) {
setLoading(false);
console.log(error);
}
};
return (
<Fragment>
<div>
<button onClick={fetchApi}>funciona pls</button>
{allData.map((data) => (
<div
style={{
backgroundColor: "#c7c7c7",
display: "flex",
flexDirection: "column",
padding: 16,
margin: 5,
borderRadius: 20
}}
>
<p>
<strong>Address: {data.street_address}</strong>
</p>
<p>
<strong>City: {data.city}</strong>
</p>
<p>
<strong>Street Name: {data.street_name}</strong>
</p>
<p>
<strong>Zipcode: {data.zip_code}</strong>
</p>
<button onClick={removeElement}>botao</button>
</div>
))}
</div>
</Fragment>
CodePudding user response:
In your removeElement
method, you are setting your state allData
to an empty array. Every time you run removeElement
you will be clearing your state.
If each element in allData
has a unique id, your removeElement
method could look something like this:
const removeElement = (id) => {
const newData = allData.filter(element => element.id === id);
setAllData(newData);
};
And your component:
return (
<Fragment>
<div>
<button onClick={fetchApi}>funciona pls</button>
{allData.map((data) => (
<div
style={{
backgroundColor: "#c7c7c7",
display: "flex",
flexDirection: "column",
padding: 16,
margin: 5,
borderRadius: 20
}}
>
<p>
<strong>Address: {data.street_address}</strong>
</p>
<p>
<strong>City: {data.city}</strong>
</p>
<p>
<strong>Street Name: {data.street_name}</strong>
</p>
<p>
<strong>Zipcode: {data.zip_code}</strong>
</p>
<button onClick={()=>removeElement(data.id)}>botao</button>
</div>
))}
</div>
</Fragment>