Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh Screen A when goBack with React Native using Hooks

I have a simple doubt that I can hope somebody can help me with. I have a simple app that hava a main screen where loads all data that I get from a SQLite database, but, when I go to the 'Add To The Database Screen' and add some data and record in the database, I use a function to go back to the previous screen (props.navigation.goBack()).

Unfortunately, when I arrive at the screen A, my hook does not 'refresh' or update the data from the database. Is there a way to make it refresh the screen A to make a new call to the database and refresh data with the new data?

ps: to make the call to database, I use the today date to get data in a query, so my date does not update.

Here's my code:

ScreenA.js

import React, { useEffect, useState } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';

export default function ScreenA() {

   const [data, setData] = useState([]);

    useEffect(() => {
        setData(getDataFromApi())
    }, []);

    return(
        <View>
            { apiResponse() }
            <TouchableOpacity onPress={() => { props.navigation.navigate('ScreenB') }}
                <Text>Add data</Text>
            </TouchableOpacity>
        </View>
    )
}

And here is the ScreenB.js

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

export default function ScreenB() {

    function goBackToScreenA() {
        addDataToDatabase();
        props.navigation.goBack();
    }

    return(
        <View>
            <TouchableOpacity onPress={() => { goBackToScreenA() }}>
                <Text>Go Back</Text>
            </TouchableOpacity>
        </View>
    );
}
like image 778
ofernandoavila Avatar asked Dec 13 '22 08:12

ofernandoavila


1 Answers

If you are using reactnavigation then you can subscribe to the navigation lifecycle

 React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
  // Screen was focused
  // Do something
});

    return unsubscribe;
  }, [navigation]);

https://reactnavigation.org/docs/navigation-lifecycle

like image 149
Sam van beastlo Avatar answered Jan 31 '23 18:01

Sam van beastlo