So, I'm trying to update a product with mongodb and redux, but when I try to update the product, the database doesn't seem to change. I can't solve this, please can you help me?
Below I have my product.js file:
//UPDATE
router.put('/:id', verifyTokenAndAdmin, async (req, res) => {
try {
const updatedProduct = await Product.findByIdAndUpdate(
req.params.id,
{
$set: req.body,
},
{ new: true }
);
res.status(200).json(updatedProduct);
} catch (err) {
res.status(500).json(err);
}
});
apiCalls.js:
export const updateProducts = async (id, product, dispatch) => {
dispatch(updateProductStart());
try {
const res = await userRequest.put(`/products/${id}`);
dispatch(updateProductSuccess({ id, product }));
} catch (error) {
dispatch(updateProductFailure());
}
};
requestMethods.js:
import axios from 'axios';
const BASE_URL = 'http://localhost:5000/api/';
const TOKEN =
JSON.parse(JSON.parse(localStorage.getItem('persist:root')).user).currentUser
.accessToken || '';
// set token
localStorage.setItem('ACCESS_TOKEN', TOKEN);
// get token
const myToken = localStorage.getItem('ACCESS_TOKEN');
export const publicRequest = axios.create({
baseURL: BASE_URL,
});
export const userRequest = axios.create({
baseURL: BASE_URL,
headers: { token: `Bearer ${myToken}` },
});
CodePudding user response:
Change updateProducts
as below. Notice there is a second parameter given to put
. This would be equal to req.body
in the backend part.
export const updateProducts = async (id, product, dispatch) => {
dispatch(updateProductStart());
try {
const res = await userRequest.put(`/products/${id}`, product);
dispatch(updateProductSuccess({ id, product }));
} catch (error) {
dispatch(updateProductFailure());
}
};
And in the backend try changing findByIdAndUpdate
as below. And before log req.body
to see if you are getting the data.
const updatedProduct = await Product.findByIdAndUpdate(req.params.id, req.body);