Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function when opening a react-native screen

I'm trying to load a JSON from AsyncStorage every time a user opens one of my react-native screens (I'm using StackNavigator). This JSON contains information on what my states should be set to.

How can I call a function that runs every time this screen is opened?

Further info: I've written a function that updates my states according to a JSON loaded from AsyncStorage. The function works perfectly when called from a button, but when the function is called from render(), part of my screen freezes and some buttons are not touchable anymore. Strangely only TextInput still works.

like image 223
Filip Frahm Avatar asked Jun 28 '17 15:06

Filip Frahm


3 Answers

use componentWillMount() method. This will execute automatically before render() method gets triggered.

class Sample extends Component{
    state = {data : []};
    componentWillMount(){
        this.setState({data : inputObject});
    }
    render(){
        return(
            <View>
            //you can render the data here
            </View>
        );
    }
}

import { useEffect, useState } from 'react';

const Sample = () => {
    const [state, setState] = useState([]);
    useEffect(() => {
        setState(inputObject);
    }, [])

    return(
         <View>
         //you can render the data here
         </View>
    );

}

Reference: https://facebook.github.io/react/docs/react-component.html#componentwillmount

like image 182
divine Avatar answered Sep 17 '22 15:09

divine


If you want to handle back button page navigation then you need to listen to the navigation event once when the component has mounted, use the code below for the same.

componentDidMount = () => {
    this.focusListener = this.props.navigation.addListener('focus',
       () => { 
               console.log('focus is called'); 
              //your logic here.
       }
     );
}
like image 33
manish kumar Avatar answered Sep 17 '22 15:09

manish kumar


This can be easily accomplished using 'withNavigationFocus' , found in the react native documentation here

import React, { Component } from 'react';
import { View } from 'react-native';
import { withNavigationFocus } from 'react-navigation';

class TabScreen extends Component {
  componentDidUpdate(prevProps) {
    if (prevProps.isFocused !== this.props.isFocused) {
      // Use the `this.props.isFocused` boolean
      // Call any action
    }
  }

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

// withNavigationFocus returns a component that wraps TabScreen and passes
// in the navigation prop
export default withNavigationFocus(TabScreen);
like image 45
Jar Avatar answered Sep 16 '22 15:09

Jar