Home > Blockchain >  useEffect does not get triggered when getting redirected from another page using Ionic
useEffect does not get triggered when getting redirected from another page using Ionic

Time:12-11

This is using ionic and react.

I am trying to refresh data on PageA when coming back from PageB. But this does not work without doing a hard refresh on PageA after getting redirected from PageB.

I am getting data using useEffect

//empty array in use state means it will runs once after the component is loaded
  useEffect(() => {
    console.log(process.env)
    fetch(`${process.env.REACT_APP_API_URL}/invoicems/receipt`)
      .then(res => res.json())
      .then(result => {
        setIsLoaded(true)
        setItems(result)
        console.log(result)

      }, (error) => {
        setIsLoaded(true)
        setError(error)
      })
  }, [])

The data is fetched fine and displays correctly. There is an add button on the same page. the code for that is as follows

  <IonFab vertical="bottom" horizontal="end" slot="fixed">
    <IonFabButton routerLink="/add-receipt">
      <IonIcon icon={add}></IonIcon>
    </IonFabButton>
  </IonFab>

The correct redirects to the add-receipt page. That page has data input to create data. Once the data is added then I redirect to the above page using this code.

const saveHandler=()=>{
        const receipt={
            "ReceiptDate": receiptDate.current!.value,
            "Amount":amount.current!.value,
            "MerchantId":selectedMerchant,
            "ReceiptData":receiptImage?.base64,
            "Description":description.current!.value   
        }
        console.log(receipt)
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(receipt)
        };
        fetch(`${process.env.REACT_APP_API_URL}/invoicems/receipt`, requestOptions)
            .then(async (response) => {
                if (!response.ok) {
                    var error = await response.json();
                    throw Error(JSON.stringify(error))
                }else{
                    history.length>0? history.goBack() : history.replace('home')
                } 

            })
            .catch(error => {
               console.log(error);
            });
    }

The problem is the data on the first page isn't refreshed without doing a refresh. How can this be fixed?

CodePudding user response:

The problem is in the history.goBack(). That method will not call your useEffect because it hasn't been unmounted and then mounted, that page was there the whole time.

I suggest using another method like history.go() or another one that doesn't break your history journal.

Another possibility would be using useEffect but having the history as a dependency, instead of []. That way, you can trigger that fetch whenever the history matches your path, for example. You can get the history with the useHistory hook.

CodePudding user response:

Found a way to get around this problem by doing the following. [location.key] changes every time you switch between pages. Hence using that as a dependency is what was needed in this case. Got to know about uselocation from https://dev.to/zbmarius/react-route-refresh-without-page-reload-1907

It's mentioned in the comments section by Adam Rich

import { useLocation } from 'react-router';

const location = useLocation();

 const location = useLocation();
  useEffect(() => {
    console.log(location.key)
    getData();
  },[location.key])
  • Related