its first time for me using react-router-dom v6, I am familiar with v4.
I have a list of movies and every movie has an id, I need to be navigated to not-found page if the users entered a wrong movie id in the url.
The problem that I am using a class component so I am stuck to use componentDidMount which causes the following error
You should call navigate() in a React.useEffect(), not when your component is first rendered.
here is my code:
componentDidMount() {
let { id } = this.props.params;
const genres = getGenres();
this.setState({ genres });
const movieId = id;
if (movieId === 'new') return;
const movie = getMovie(movieId);
if (!movie) return this.props.navigate('/not-found', { replace: true });
this.setState({ data: this.mapToViewModel(movie) });
}
I am using a class component as I mentioned, so I exported the class as a function to make the Useparams() work with me
function WithNavigate(props) {
let navigate = useNavigate();
return <MovieForm {...props} params={useParams()} navigate={navigate} />;
}
export default WithNavigate;
My question now how to make the navigate works in the componentDidMount!
Thank you in advance