useEffect not executing when I use back button to navigate

Viewed 2435

I am trying to load a page full of buttons. When you click on a button, you go to a page associated with a particular country. Pressing the back arrow on the browser should take you back to the button page, but that page is blank until I refresh it. I'm assuming the useEffect doesn't execute when I go back a page, but I'm not sure. Here is my button page:

import React from 'react';
import { useState, useEffect } from 'react';
import Country from './Country.js';
import { Link } from 'react-router-dom'
import Button from '@material-ui/core/Button';


export default function CIALanding(props) {


    const [countriesList, setCountriesList] = useState([])

    async function getCountries() {
        const response = await fetch('http://127.0.0.1:5000/countries');
        const data = await response.json();
        setCountriesList(data['country_list'].map((country) => {return (
            <Link to={{pathname:`/country/${country[0]}`
            }}>
            <Button>{country[0]}</Button>
            </Link>
        )}))
    }

    useEffect(() => {
        getCountries()
    },[])
        return (
            <div>
            {countriesList}
            </div>
        )

}

Here is the page that the buttons navigate to

import React from 'react';
import { Link } from 'react-router-dom'
import Button from '@material-ui/core/Button'
import {useState, useEffect } from 'react';

export default function Country(props) {

    const [details, setDetails] = useState({})
    const [pdf, setPdf] = useState('')
    const { country }= props.match.params

    async function getDetails() {
        const configs = {
            methods: 'POST',
            mode: 'cors',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                'country': country
            })
        };
        const response = await fetch('http://127.0.0.1:5000/details', configs)
        const data = await response.json();
        setDetails(data['details'])
        setPdf(data.pdf)
    }

    useEffect(() => {
        getDetails()
    },[])

    return (
        <div>
            <div>{details}</div>
            <Button>Hello</Button>
        </div>
    )

}

Here are my routes

export default function App() {

const [cname, setCName] = useState('')
const [pdf, setPdf] = useState('')
const [details, setDetails] = useState('')

  return (
    <div className="App">
      <BrowserRouter>
        {/* <Route exact path="/" component = { Home }/> */}
        <Route path="/cia" component = {(props) => <CIALanding {...props} setCName={setCName} setPdf={setPdf} setDetails={setDetails}/>}/>
        <Route path="/country/:country" component={(props) => <Country {...props} setCName={setCName} details={details} cname={cname}/>}/>
        <Route path="/countrypage" component={CountryPage}/>          
      </BrowserRouter>
    </div>
  );
}

Thanks for the help!

1 Answers

You need to update the useEffect

import React from 'react';
import { Link } from 'react-router-dom'
import Button from '@material-ui/core/Button'
import {useState, useEffect } from 'react';

export default function Country(props) {

    const [details, setDetails] = useState({})
    const [pdf, setPdf] = useState('')
    const { country }= props.match.params

    async function getDetails() {
        const configs = {
            methods: 'POST',
            mode: 'cors',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                'country': country
            })
        };
        const response = await fetch('http://127.0.0.1:5000/details', configs)
        const data = await response.json();
        setDetails(data['details'])
        setPdf(data.pdf)
    }

    useEffect(() => {
        getDetails()
    },[props.match.params.country])

    return (
        <div>
            <div>{details}</div>
            <Button>Hello</Button>
        </div>
    )

}

For the debugging, you can try with, if it works. Don't use this in the final code as this will be called upon every prop update.

useEffect(() => {
    getDetails()
})
Related