targetMovie is null when it comes to rednering. I couldn’t find any solutions. First time having unsolvable problem. Please help!
async function getMovie(id) {
try {
const res = await axios.get(apiEndPoint + "/" + id);
const movies = await res.data;
return movies;
} catch (err) {
console.log(err);
}
}
const MovieEdit = () => {
const { id } = useParams();
const [targetMovie, setTargetMovie] = useState(null);
useEffect(() => {
getMovie(id)
.then((mov) => {
setTargetMovie(mov);
console.log(mov);
})
.catch((err) => console.log(err));
}, []);
console.log(targetMovie);
if (targetMovie) return <AddMovie movie={targetMovie} />;
return <Navigate to="/not-found" />;
};
Advertisement
Answer
You need to represent 3 states:
- You’re currently waiting on getMovie to complete
- getMovie completed successfully
- getMovie completed and returned null/undefined
You’re currently using the same condition (!targetMovie) to represent both 1. and 3. which is why you’re running into issues.
Try this:
const MovieEdit = () => {
const { id } = useParams();
const [isFetching, setIsFetching] = useState(true);
const [targetMovie, setTargetMovie] = useState(null);
useEffect(() => {
getMovie(id)
.then((mov) => {
setIsFetching(false);
setTargetMovie(mov);
console.log(mov);
})
.catch((err) => {
console.log(err));
setIsFetching(false);
}
}, []);
if (isFetching) return null;
if (targetMovie) return <AddMovie movie={targetMovie} />;
return <Navigate to="/not-found" />;
};