0

I am using a class component with react and this error popped up. Wondering, did anyone use a this inside axios before or know how to? Thank you in advance

type State = {
  fetchedPassword: string;
  fetchedPassword: string;
}

type Props = {

}

export default class MyComponent extends React.Component<Props,State>() {

constructor(props: Props) {
    super(props);
    this.state= {
      fetchedPassword: "",
      fetchedUsername: ""
    }

}

  authLogin = (e:any) => {
    e.preventDefault();
    const { fetchedUsername, fetchedPassword } = this.state;

    axios
      .get(url)
      .then(function (response) {
        this.setState({ fetchedPassword: response.data.password }); //error appears here
        this.setState({ fetchedUsername: response.data.username }); //and here
      })
      .catch(function (error) {
        console.log("Error: " + error);
      });
  }
}

The error says

'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
MyComponenet.tsx(26, 13): An outer value of 'this' is shadowed by this container.

I'm not sure how to solve this

  • Just make it an arrow function `function (response) {` to `(response) => {`. Then read [this](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback/20279485#20279485) – Brian Thompson Aug 19 '21 at 20:26
  • Does this answer your question? [How to access the correct \`this\` inside a callback](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Brian Thompson Aug 19 '21 at 20:27

2 Answers2

0

Make a copy of you component instance this and store it in that constant:

authLogin = (e:any) => {
    e.preventDefault();
    const { fetchedUsername, fetchedPassword } = this.state;

    const that = this

    axios
      .get(url)
      .then(function (response) {
        that.setState({ fetchedPassword: response.data.password });
        that.setState({ fetchedUsername: response.data.username });
      })
      .catch(function (error) {
        console.log("Error: " + error);
      });
  }
spatak
  • 1,039
  • 1
  • 14
  • 25
0

Move authLogin outside your constructor, then, as a last line in your constructor, add

this.authLogin = this.authLogin.bind(this);

See https://www.freecodecamp.org/news/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56/ for more info.

Kevin Ashworth
  • 602
  • 6
  • 11