Manvendra
Manvendra

Reputation: 1

index.js:1 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

This was my code

import React, { Component } from "react";
import axios from "axios";

class App extends Component {
  state = {
    invites: [],
  };

  constructor() {
    super();
    axios.get(`http://localhost:8080/security/allUser`).then((res) => {
      console.log(res.data);
      this.setState({ invites: res.data });
    });
  }

  render() {
    return (
      <div>
        {this.state.invites.map((invite) => (
          <h2 key={invite.id}>{invite.name}</h2>
        ))}
        <h1>Welcome</h1>
      </div>
    );
  }
}

export default App;

state and setState have worked for me alright for more complex codes before. This one keeps showing the same error

This is the error:

index.js:1 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 App component.

Upvotes: 0

Views: 1173

Answers (2)

ahmetkilinc
ahmetkilinc

Reputation: 684

Actually you can make request in constructor (React allows it but you shouldnt) but you have to make the request only after the component has been mounted or just before it is about to be mounted.

So it is wise to make your requests in componentDidMount().

import React, { Component } from "react";
import axios from "axios";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
       invites: [],
    };
  }

  componentDidMount() {
      axios.get(`http://localhost:8080/security/allUser`).then((res) => {
          console.log(res.data);
          this.setState({ invites: res.data });
    });
  }

  render() {
    return (
      <div>
        {this.state.invites.map((invite) => (
          <h2 key={invite.id}>{invite.name}</h2>
        ))}
        <h1>Welcome</h1>
      </div>
    );
  }
}

export default App;

Upvotes: 1

Mohamed Ali
Mohamed Ali

Reputation: 141

Add a componentDidMount() and write your request call inside it. When the component first loads the componentDidMount function will run.

Upvotes: 2

Related Questions