I have my Application in React JS. I am fetching data from an API at http://localhost:8080/api/list:
Here is the data that I am getting from the REST API in the Google Chrome console:
0:{
id: 4
supplierFirstname: "Tom"
supplierLastName: "ABC"
supplierTitle: "TomTheSupplier"
accountNumber: 1122234444
address: "111 ADrive, 1234 ST."
companyName: "TheTom Company & Associates"
email: "tomtomjayjay@email.com"
hourlyRate: 29
phoneNumber: 123456789
otherPhoneNumber: 1023456789
paymentTerms: "Credit"
notes: "Some Supplier"
createdAt: null
typeOfGoods: "Supplies"
website: "www.abc_123.com"
products: [{…}]
components:
[
0: {id: 5, name: "AComponent", unit: null, quantity: 0, componentCost: 0, …}
]
}
Here is my React code:
class SupplierData extends React.Component {
constructor(props) {
super(props);
this.state = {
supplier: [
{
id: 0,
supplierTitle: "Supplier Title",
supplierFirstName: "First Name",
supplierLastName: "Last Name",
companyName: "Company Name",
phoneNumber: "Phone Number",
otherPhoneNumber: "Phone Number (Other)",
accountNumber: "Account Number",
email: "Email",
address: "Address",
website: "Website",
hourlyRate: "Hourly Rate",
typeOfGoods: "Type Of Goods",
paymentTerms: "Payment Terms",
createdAt: "Created At",
notes: "Notes",
products: "Products",
components: "Components",
},
],
errorMessage: [],
};
this.ListAllSuppliers = this.ListAllSuppliers.bind(this);
}
ListAllSuppliers = async () => {
return await axios
.get(`http://localhost:8080/api/suppliers/supplier/list`)
.then((response) => {
let apiResults = response.data;
console.log(apiResults);
this.setState({ supplier: apiResults }); <--- The error happens here.
})
.catch((error) => {
this.setState({ errorMessage: this.state.errorMessage.push(error) });
});
};
componentDidMount() {
this.ListAllSuppliers();
}
}
export default SupplierData;
The problem that I am facing is in the React State. I am getting the following error:
Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might
indicate a bug in your application. Instead, assign to `this.state` directly or define a `state =
{};` class property with the desired state in the SupplierData component.
Question: I want to set the state.
What is a possible fix the above error?