I'm trying to update/edit the posts. The PUT request in the back end works fine, returning 200 and updates posts when tested on Postman however when I try to update a post in the front end (react), I'm not receiving any errors but the updated post isn't being updated on submit and the updated fields (title and body) are null.
Why are the updated values null
inside data
? How can I update the post with the new values instead of getting null?
const EditPost = ({match}) => {
const [values, setValues] = useState({
title: "",
body: "",
error: ""
});
const { user, token } = isAuthenticated();
const {
title,
body,
error
} = values;
const init = (id) => {
read(id).then(data => {
if (data.error) {
setValues({...values, error: data.error})
} else {
setValues({...values,
title: data.title,
body: data.body
})
// NOTE: I get null for the title and body values when I console.log(data)
console.log(data)
}
})
}
useEffect(() => {
const id = match.params.id;
init(id);
}, []);
const handleChange = (name) => (event) => {
setValues({ ...values, [name]: event.target.value });
console.log({...values})
};
const clickSubmit = (event) => {
event.preventDefault();
setValues({ ...values, error: "" });
editPost(match.params.userId, match.params.id, token).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues({
...values,
title: "",
body: "",
error: false,
});
}
});
};
const newPostForm = () => (
<form onSubmit={clickSubmit}>
<div className="form-group">
<label className="text-muted">Title</label>
<input
onChange={handleChange("title")}
type="text"
className="form-control"
value={title}
/>
</div>
<div className="form-group">
<label className="text-muted">Post Body</label>
<textarea
onChange={handleChange("body")}
className="form-control"
value={body}
/>
</div>
<button>Update Post</button>
</form>
);
const showError = () => (
<div
style=>
{error}
</div>
);
return (
<div>
<div>
{showError()}
{newPostForm()}
</div>
</div>
);
};
export default EditPost;
const Post = props => {
const [post, setPost] = useState({});
const [error, setError] = useState(false);
console.log(post)
const loadSinglePost = id => {
read(id).then(data => {
if (error) {
console.log(data.error)
setError(data.error);
} else {
setPost(data);
}
});
};
useEffect(() => {
const id = props.match.params.id;
loadSinglePost(id);
}, [props]);
return (
<div>
<Navbar />
<div className="post-container">
<h3 className="post-title">{post && post.title}</h3>
<p className="post-date">{post && post.date}</p>
<p className="post-body">{post && post.body}</p>
<p> {post.author ? post.author.name : ""}</p>
</div>
</div>
)
}
export default Post
export const read = id => {
return fetch(`${API}/blog/post/${id}`, {
method: 'GET',
Accept: "application/json",
"Content-Type": "application/json",
})
.then(response => {
return response.json()
})
.catch(err => console.log(err))
}
export const editPost = (userId, id, token, post) => {
return fetch(`${API}/${userId}/${id}/edit`, {
method: 'PUT',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify(post)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
Backend code
// controller
exports.readById = (req, res) => {
Post.findById(req.params.id)
.then(post => res.json(post))
.catch(err => res.status(400).json('Error: ' + err));
}
exports.edit = (req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send(`ID is not valid: ${req.params.id}`)
const {title, body} = req.body
const updatedPost = {title, body }
Post.findByIdAndUpdate(req.params.id, {
$set: updatedPost
}, {new:true}, (error, data) => {
if (error) {
return error
} else {
res.send(data)
console.log(data)
}
})
}
from mern - cannot update post, values are null
No comments:
Post a Comment