1

I need to call fectchData when there's no testData in context store or input ur is different from saved testData[0].ur. But this constantly request API if there's ur has empty testData. Which condition will make trick?

componentDidMount() {
    const [state] = this.context;
    const { testData } = state;

    const fetchData = async () => {
      console.log("fetching data");
      this.setState({ loading: true });
      this.updateTestData();
    };

    if (testData === "" || testData[0]?.ur !== this.props.ur) fetchData();
  }
  • why you have defined your function and states inside `componentDidMount`? each time you call the setState, it causes rerendering and it will call your API again... – Abbasihsn Aug 10 '21 at 09:57
  • it sounds reasonable, then how to handle loading state without compnentDidMount? – jacobliu609 Aug 10 '21 at 14:50

1 Answers1

0

try this and let me know the results:

const [state] = this.context;
    const { testData } = state;

    const fetchData = async () => {
      console.log("fetching data");
      this.setState({ loading: true });
      this.updateTestData();
    };

componentDidMount() {
    if (testData === "" || testData[0]?.ur !== this.props.ur) {
       fetchData();
    }
  }
Abbasihsn
  • 2,075
  • 1
  • 7
  • 17