I have this issue where React does not update/refresh the page when manually entering a URL on a tab that already has the website open.
I have a live demo of the website here: https://dpldmuafup7cw.cloudfront.net/#/
When on the home page you should be able to click a link to a film, and then enter the ID of another film, e.g. accessing https://dpldmuafup7cw.cloudfront.net/#/film/9 and replacing the URL to be https://dpldmuafup7cw.cloudfront.net/#/film/574 should cause the page to update with the new film's information. Instead, this only works if you enter the new URL, press enter, then refresh. I've seen online that I can use HashRouter which did alleviate the problem of nothing loading at all when manually entering a URL.
I've tried some fixes I've seen online such as using historyApiFallback but this isn't really possible as react is running on AWS. HashRouter also doesn't seem to be working.
Excerpt from app.tsx:
<HashRouter>
<Switch>
[...]
<Route exact path="/film/:id">
<Film />
</Route>
</Switch>
</HashRouter>
Film component:
const Film: React.FC = () => {
const [film, setFilm] = useState(null as unknown as any);
const [filmPoster, setFilmPoster] = useState('');
// get film id from route param:
const { id } = useParams<{ id: string }>();
// must use useEffect hook to use async functions
// rather than returning await asyncFunc()
useEffect(() => {
async function getFilmPoster() {
setFilmPoster(await getIMDbFilmPoster(id));
let response = await fetch(`${getFilmByIDURL}/${id}`, {
method: 'get'
});
response = await response.json();
setFilm(response);
}
getFilmPoster();
}, []);
return (
[JSX goes here...]
<h1>{film ? film.title : null}</h1>
Webpack:
module.exports = {
devtool: 'inline-source-map',
entry: './src/index.tsx',
output: {
filename: 'index.bundle.js',
assetModuleFilename: 'images/[hash][ext][query]'
},
target: 'web',
devServer: {
historyApiFallback: true,
hot: true,
open: true,
port: 3000
},
performance: {
hints: false
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json']
},
module: {
rules: [
[...]
]
}
};
Any help would be greatly appreciated, I'm not sure why its not working as intended
Additionally, I'm aware that CSS is very broken in parts, it is still in the early stage of development and currently features are more important than polish
CodePudding user response:
I think you must pass the id parameter inside the [] (second argument) of the useEffect. Thus it will update every time you switch to another page.