0

I'm new to the react.

I have this state :

     state = {
    isLoading: true,
  };

And I have this lifecycle function

 componentDidMount() {
    const { setPageCount, receiveApiData } = this.props.actions;
    const { isLoading } = this.state;
    const getData = () => {
      this.setState({ isLoading: !isLoading });
      receiveApiData();
      setPageCount();
    };
    setInterval(() => {
      getData();
    }, 30000);
  }

Here is what I'm trying to return in render():

 return isLoading ? (
  <Loading></Loading>
) : ( `Some Code here`)

The problem is state is Always true and my lifecycle method is not changing it to the false so my app can not render the false condition. I don't know what to do,any suggestions please?

Everything else in getData() is working correctly

2 Answers 2

1

The issue is here:

this.setState({ isLoading: !isLoading });

because isLoading what you are destructuring taking previous value i.e it is not taking latest state value so its not updating your isLoading . What you need to do is this:

this.setState({ isLoading: !this.state.isLoading });

Here is the demo: https://codesandbox.io/s/interesting-chandrasekhar-pluv7?file=/src/App.js:312-332

Sign up to request clarification or add additional context in comments.

Comments

1

Since your new state depends on the value of your old state, you should use the functional form of setState

this.setState(prevState => ({
  isLoading: !prevState.isLoading
}));

Official documentation: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.