I'm just learning react at the moment, I have built a layout page and then display images using a component. Inside the component, each image has a button. this button deletes the image from the API.
But although the API call is working, and the image is deleted from the database, its not removing that image component from the layout.
Im using axios to interact with the API. Any help would be greatly appreciated.
My layout code is as follows;
import React, { Component } from "react";
import axios from 'axios';
import ImageComponent from './components/ImageComponent';
class ImageOverview extends Component {
constructor(props) {
super(props);
this.state = {
imageData: []
};
}
componentDidMount() {
axios.get('http://api.com/getAllImages')
.then(res => {
const imageData = res.data;
this.setState({ imageData });
})
}
render() {
return (
<>
<div className="content">
<Row>
<Col lg="12">
<Card>
<CardBody>
<Row>
{ this.state.imageData.map(image =>
<ImageComponent
key={image.id}
image={image}
/>
)}
</Row>
</CardBody>
</Card>
</Col>
</Row>
</div>
</>
)
}
}
export default ImageOverview;
and my component code is here;
import React, { Component } from "react";
import axios from 'axios';
class ImageComponent extends Component {
deleteImage(id)
{
axios.delete('http://api.com/deleteimage' + id)
.then(res => {
console.log(res);
})
}
render() {
const { image } = this.props;
return (
<>
<Col className="col-xs-6 col-xs-6">
<Card className="h-80">
<CardImg top width="100%" src={'http://imagelocation.com/' + image.filename} alt="Card image cap" />
<CardBody>
<Button color="danger" size="sm" onClick={() => this.deleteImage(image.id)}><i className="icon-simple-remove" /> Delete</Button>
</CardBody>
</Card>
</Col>
</>
)
}
}
export default ImageComponent;
this.state.imageDataarray of parent component too. Since you can't change state of parent from child, move thedeleteImagemethod to parent and pass it down as prop toImageComponent. Once you have lot of data and components and it starts getting to complex to pass stuff down to child as props, you might wanna maintain a global state using Redux, but don't worry about it just yet.