React native How to execute function every time when i open page

I need to send request every time when i open page. Currently when i access page first time after load the app everything is ok, but if i go to another page and back after that request is not send it again.

Upvotes: 4

Views: 15517

Answers (3)

y4h2
y4h2

Reputation: 3383

Just as a supplement to Nooruddin's answer.

In react-navigation 5.x/6.x, you can use the useFocusEffect hook, instead of adding event listeners manually.

import * as React from 'react';
import { View } from 'react-native';
import { useFocusEffect } from '@react-navigation/native';

function Profile() {
  useFocusEffect(
    React.useCallback(() => {
      // Do something when the screen is focused

      return () => {
        // Do something when the screen is unfocused
        // Useful for cleanup functions
      };
    }, [])
  );

  return <View />;
}

source: https://reactnavigation.org/docs/navigation-lifecycle#react-navigation-lifecycle-events

Upvotes: 1

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

You have to add focus listener so when you go back, It will refresh the data like

import * as React from 'react';
import { View } from 'react-native';

function AppScreen({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // The screen is focused
      // Call any action and update data
    });

    // Return the function to unsubscribe from the event so it gets removed on unmount
    return unsubscribe;
  }, [navigation]);

  return <View />;
}

source : https://reactnavigation.org/docs/function-after-focusing-screen/

Upvotes: 14

user14361391
user14361391

Reputation:

Here you go, example for a class based and functional based component to run something on every load of the screen.

import React, { useEffect } from "react";
import {View} from 'react-native'

//Functional Component
const App = ()  => 
{

  useEffect(() =>
  {
     myAction();
  }, [])



  return (
    <View>

    </View>
  );
}

//Class based Component
 class App extends Component
 {

  componentDidMount()
  {
    this.myAction();
  }

  render()
  {
    return(
      <View>
        
      </View>
    )
  }

 }

Upvotes: 4

Related Questions