Reputation: 77
I am building a React web application that has CRUD operations on a table connected to a database. I am using axios in React components to make ajax calls to the backend controller. The Customers component displays a list of records from my table. When I create, delete or edit a record from the database the Customers component is not automatically refreshing. I have to refresh the page in order to get the updated records my database. I had a look at lifting the state up but I don't understand why its not working as the Customers component is already the parent.
import React, { Component } from 'react';
import axios from 'axios';
import { Table, Header } from 'semantic-ui-react';
import EditCustomerModal from './EditCustomerModal';
import AddCustomerModal from './AddCustomerModal';
import DeleteCustomerModal from './DeleteCustomerModal';
export class Customers extends Component {
constructor(props) {
super(props);
this.state = { customers: [] };
}
componentDidMount() {
this.populateCustomerData();
}
render() {
let customers = this.state.customers;
return (
<div>
<Header as='h2'>Customer Table</Header>
<p>This component demonstrates CRUD operations from the customer table.</p>
<AddCustomerModal />
<Table striped>
<Table.Header>
<Table.Row>
<Table.HeaderCell>ID</Table.HeaderCell>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Address</Table.HeaderCell>
<Table.HeaderCell textAlign="center">Actions</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{customers.map((customer) => {
return (
<Table.Row key={customer.id}>
<Table.Cell>{customer.id}</Table.Cell>
<Table.Cell>{customer.name}</Table.Cell>
<Table.Cell>{customer.address}</Table.Cell>
<Table.Cell textAlign="center">
<EditCustomerModal details={customer} />
<DeleteCustomerModal customerID={customer.id} />
</Table.Cell>
</Table.Row>
)
})}
</Table.Body>
</Table >
</div>
);
}
populateCustomerData = () => {
axios.get("Customers/GetCustomers")
.then((result) => {
this.setState({ customers: result.data })
})
.catch((error) => {
console.log(error);
});
}
}
Upvotes: 1
Views: 1418
Reputation: 141
You need to pass a changeState function from your Customers Component to your modals and call it after a crud operation has been done.
OR
You can pass your populateCustomerData function to the modals and make them call it after the crud operation has been done.
Upvotes: 1