M
M
Matvey Ptushkin2020-06-16 20:34:12
Frontend
Matvey Ptushkin, 2020-06-16 20:34:12

What causes the error "Cannot call setState on a component that is not yet mounted"?

I'm a newbie, just started learning React. And I can’t figure out how to remove this error, everything works with it, but I want to get rid of it, I have this.state in the Rate component, what could be the problem?

import React from "react";
import "./Rate.css";
import Calc from "../calc/Calc";

class Rate extends React.Component {
constructor(props) {
super(props);

this.state = {
date: "",
currencyRate: {},
};
this.getRate();
this.currency = ["USD", "RUB", "CAD", "PHP"];
}

getRate = () => {
fetch(" https://api.
.then((data) => {
return data.json();
})
.then((data) => {
console.log(data);
this.setState({ date: data.date });
let result = {};
for (let i = 0; i < this.currency.length; i++) {
result[this.currency[i]] = data.rates[this.currency[i]];
}
this.setState({ currencyRate : result });
});
};

render() {
return (

Currency rate at {this.state.date}

{Object.keys(this.state.currencyRate).map((keyName, i) => (

{keyName}

{this.state.currencyRate[keyName] .toFixed(2)}

Can be bought for 1 EUR *

))}



);
}
}

export default Rate;

5ee9023e157d4635349471.png
5ee902e7261fa244619617.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-06-16
@Matwey_Ptushkin

everything that goes somewhere to get data - in componentDidMount

constructor() {
  ..
  // this.getRate(); из конструктора убрать
}

componentDidMount() {
  this.getRate();  // сюда добавить
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question