When my component loads, I make a call to my webApi, which returns an array of clients. I need to load that array into state, which then renders my screen with a list of clients.
So, in my constructor, I create my default state.
export default class Clients extends Component {
constructor(props) {
super(props);
this.state = {
clients: [{
id: null,
username: null,
name: null
}]
}
Then, I need to call my api as soon as possible, populate my state, so that my list can be displayed on screen. So I am putting the api call, and setState into my componentWillMount
componentWillMount() {
const request = {
method: 'GET',
URL: `${Server.ApiURL}/api/admin/clients`
};
console.log('Calling fetch....', this.state);
fetchData(request)
.then((data) => {
console.log("Data recieved!", data);
this.setState(
{ clients : data });
});
}
My log line where I say 'Data is recieved' shows the data as I'd expect in the console. An array of objects that match the objects I defined in my state.
However, I get an error when I attempt to setState.
Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
I'm sure I have done this before. But am not sure why I am getting that error. Is the way I am attempting to populate state incorrect?
My thinking is I set the initial state of the state in the constructor, and then populate my data in componentWillMount.
Why am I getting the error, and how should I be achieving this?
console.logincomponentWillUnmountto see if that's true.componentWillMountis deprecated and its bets to start api calls incomponentDidMount