I want to redirect a user to "/myblogs"
page when they submit a post after editing. useNavigate
hook was used to redirect. Instead of redirecting, I get the following error.
When I manually check my blog page, I can see the updated post. I have no idea why this error occurs
const handleSubmit = e => {
e.preventDefault();
console.log(inputs);
sendRequest().then(data =>
console.log(data).then(() => navigate('/myBlogs/'))
);
};
error in my console
BlogDetail.jsx:51 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')
Here is my full code
const BlogDetail = () => {
const navigate = useNavigate();
const [blog, setBlog] = useState();
const id = useParams().id;
console.log(id);
const [inputs, setInputs] = useState({});
const { title, descritpion, imageURL } = inputs;
const handleChange = e => {
setInputs(inputs => ({
...inputs,
[e.target.name]: e.target.value,
}));
};
const fetchDetails = async () => {
const res = await axios
.get(`http://localhost:5000/api/blog/${id}`)
.catch(err => console.log(err));
const data = res.data;
return data;
};
useEffect(() => {
fetchDetails().then(data => {
setBlog(data.blog);
setInputs({
title: data.blog.title,
descritpion: data.blog.description,
imageURL: data.blog.image,
});
});
}, [id]);
const sendRequest = async () => {
const res = await axios
.put(`http://localhost:5000/api/blog/update/${id}`, {
title: inputs.title,
descritpion: inputs.description,
})
.catch(err => console.log(err));
const data = await res.data;
return data;
};
console.log(blog);
const handleSubmit = e => {
e.preventDefault();
console.log(inputs);
sendRequest().then(data =>
console.log(data).then(() => navigate('/myBlogs/'))
);
};
CodePudding user response:
console.log
is a void return (i.e. returns undefined
), it doesn't return any Promise object to chain from. Just issue the imperative navigation after the log statement.
const handleSubmit = e => {
e.preventDefault();
console.log(inputs);
sendRequest()
.then(data =>
console.log(data);
navigate('/myBlogs/');
);
};
CodePudding user response:
i changed my code to
sendRequest().then((data) => console.log(data)).then(() => navigate('/myBlogs/'))
from this
sendRequest().then(data =>
console.log(data).then(() => navigate('/myBlogs/'))
);
and it works