Q:

React page doesn't load the new content

I'm trying to redirect page declaratively.
Here is my Header.js:
const Header = () => {  
    const [data, setData] = useState({ objects: [] });
    useEffect(async () => {
        const result = await axios.get(
            "http://example.com/api/v1/categories"
        );
        setData(result.data);
    }, []);

    return (
        <div>
            {courses.map( objects => (
                <Link to={`/cats/${objects.id}`}>{objects.title}</Link>
            ))}
        </div>
    );
};

export default Header;

Here is my App.js
class App extends Component {
    render(){
        return (
            <Router>
                <Redirect exact from="/" to="/index" />
                <Route path = "/" component = {App}>
                    <Header/>
                    <Route path="/cats/:objectId" component={CoursePage} />
                </Route>
            </Router>
        );
    }
}
export default App;

Here is the CoursePage.js:
const CoursesPage = (props) => {

    let { objectId } = useParams();

    const [data, setData] = useState({ courses: [] });

    useEffect(() => {
        (async () => {
            const result = await axios.get(
                "http://example.com/api/v1/cats/"+objectId
            ).catch(err => {
                console.error(err);
            });
            setData(result.data);
        })();
    }, []);

    return (
        <Fragment>
            {courses.title}
        </Fragment>
    );
};

export default CoursesPage;

On Header I click to links. It redirects to course page successfully. But when I click again another course link, it doesn't reload the component and it doesn't load the new data. The URL changes, but page is not.
How can I force the page to reload the component?

A:

You should change the dependency array of useEffect in CoursePage to depend on objectId, whenever object id will change, it will rerun the effect.
const CoursesPage = (props) => {

let { objectId } = useParams();

const [data, setData] = useState({ courses: [] });

useEffect(() => {
    (async () => {
        setData({ courses: [] });    // add this line
        const result = await axios.get(
            "http://example.com/api/v1/cats/"+objectId
        ).catch(err => {
            console.error(err);
        });
        setData(result.data);
    })();
}, [objectId]);  // Update dependency array here

return (
    <Fragment>
        {courses.title}
    </Fragment>
);
}
 
export default CoursesPage;

This will reset the previous data before to load new one as soon as object id changes.
If you want to remount component completely on param change in url, then you can add an id to your component root element.
return (
<Fragment key={objectId}>
    {courses.title}
</Fragment>
);

More Info here...

