Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native refresh content when user hits back button - using Hooks

I would like to refresh the data, when user is back from one page to another. This is how my useEffect function looks like now:

useEffect(() => {
    setIsLoading(true);

    AsyncStorage.getItem("user").then((response) => {
        const currentData = JSON.parse(response);
        setUser(currentData)
        fetch('URL',
            {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_id: currentData.id
                }),
            }
        )
            .then(response => response.json())
            .then(data => {
                 setNotis(data.notifications);
                 setIsLoading(false)
            })
            .catch(error => {
            });
    });
}, []);

This function should run every time when user is on the page. Doesn't matter if it was onBackPressed or not.

Thanks

like image 911
csirkeautomata Avatar asked Oct 24 '25 15:10

csirkeautomata


1 Answers

Using React-navigation

We can directly refresh screen if you're using react-navigation

Import @react-navigation/native

import React, { useEffect } from "react";
import { useIsFocused } from "@react-navigation/native";

const HomeScreen = (props) => {
const isVisible = useIsFocused();

useEffect(() => {
    console.log("called when screen open and also on close"); 
    // this will call on both screen open and screen close.

   if (isVisible) {
      console.log("called when screen open or when back on screen "); 
   }

}, [isVisible]);

return (
    ......
)

}

I hope it will help.

like image 116
Jogendra.Com Avatar answered Oct 26 '25 05:10

Jogendra.Com



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!