Kevin Gozali
Kevin Gozali

Reputation: 319

How to fire componentDidMount() or useEffect Hook on every visit to a page/screen?

So I have an app with an activity. The app checks for Internet connection at the beginning. If there are no Internet connection, it will show a screen with a button to refresh the page. The problem is that my API calls (Axios) is located on componentDidMount() where it's called only once after the first render. Is there any way I can reload the page so it calls componentDidMount again?

I mean like total refresh. I am using EXPO btw. Any help is appreciated. Sorry there are no examples, I just wanted to get the idea if possible

Upvotes: 15

Views: 110039

Answers (8)

Shivo'ham
Shivo'ham

Reputation: 3062

try with this example and check this too check this too

 componentDidMount() {
            this.props.navigation.addListener("focus", () => {
                // do something here
            });
        }

Upvotes: 3

Zahir Masoodi
Zahir Masoodi

Reputation: 858

Based on the number of views to this question, a lot of people are redirected here, like I was. So, my answer might not be relatable but it surely will help someone.

To re-render a screen I used useIsFocused hook from @react-navigation/native

useEffect(() => {
    if (isFocused){
        console.log("Assi Gai Badal");
        //Update the state, it will cause a re-render
    }
}, [isFocused]);

It can be used in a class based component by using the withNavigationFocus higher-order component. This HOC wraps the desired Component class and passes the isFocused prop to it.

Upvotes: 0

NL_Dev
NL_Dev

Reputation: 182

I was also stuck in the same problem then i figured it out that you just need Hooks or useState to resolve the refresh issue. In my case of refreshing random deck

    const [random1, setRandom1] = useState(
    Math.floor(Math.random() * deck.length) + 1
    );

    <Image source={deck[random1]} style={styles.img} />

    <Button
    title="Refresh?"
    onPress={() => {
      setRandom1(Math.floor(Math.random() * deck.length) + 1);
    }} />

I hope this might be helpful.

Upvotes: -1

Vipul
Vipul

Reputation: 819

I was using the Functional component and did the following. I used a state as a dependency in useEffect and changed that state on button press.

const [internetCheck, setInternetCheck] = useState(0);
useEffect(() => {
  //code
}, [internetcheck]);

return(
  <Button title='Retry' onPress(() => setInternetCheck(internetCheck + 1)) />
)

Upvotes: 0

Obot Ernest
Obot Ernest

Reputation: 498

You can simply refresh a React Native or Expo app by doing the following in a functional component.

Step 1

const [refreshPage, setRefreshPage] = useState("");

Step 2 Then use it in whatever component you want to use and refresh the page, e.g in alert

                Alert.alert(
                    "End of News",
                  "You have read all latest news for today ",
                  [
                    {
                      text: "Refresh Page",
                      onPress: () => {
                        setRefreshPage("refresh");
                        
                      },
                    },
                  ],
                  { cancelable: false }
                );

It will bring alert, when the user clicks refresh page button, the page will be refreshed.

Upvotes: -1

Nunchucks
Nunchucks

Reputation: 1230

I would suggest putting your API call in it's own function fetchData within your component. fetchData can also setState after a successful fetch which will cause a re-render and show the fresh data. If you want to fetch fresh data on componentDidMount and also on a button click, then create a fetchData function and call that from within componentDidMount, then for your button just set your onPress prop appropriately onPress={this.fetchData}

Upvotes: 3

Sunil tc
Sunil tc

Reputation: 2602

You can force update the component. Check this: https://reactjs.org/docs/react-component.html#forceupdate

It will re-render the component.

check this example:

class App extends Component{
  constructor(){
    super();
        this.forceUpdateHandler = this.forceUpdateHandler.bind(this);
  };

  forceUpdateHandler(){
    this.forceUpdate();
  };

  render(){
    return(
      <div>
          <button onClick= {this.forceUpdateHandler} >FORCE UPDATE</button>
            <h4>Random Number : { Math.random() }</h4>
          </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

Upvotes: 3

Shadow_m2
Shadow_m2

Reputation: 397

Remember by calling setState function on your component, you can refresh it. if there's a button that's going to refresh the page, i would do this:

<Button  onPress={() => this.setState({dummy: 1})} />

calling setState will update your component no matter what you object you pass to it. I'm not sure if re-rendering page, calls componentDidMount function, so maybe you need to move your API calls to some funciton func and call this function in your componentDidMount, and also after each button press event. example:

componentDidMount() {
  apiCalls()
}

apiCalls() {
   .... // your code
   this.setState({dummy: 1})
}

render() {
  <View>
    ...
    <Button  onPress={this.apiCalls.bind(this)} />
    ...

  </View>
}

Upvotes: 0

Related Questions