I'm fetching data from Mongodb but the data is showing me undefined, when I try it in Postman it's working but in the app it's not.
API Side The Router
:
router.get("/:shopName", async (req, res) => {
const shopIdOrName = req.params.shopName;
var shop;
try {
// check if its valid id, else its name
if(mongoose.isValidObjectId(shopIdOrName)){
shop = await Shop.findById(shopIdOrName )
} else {
shop = await Shop.findOne({ shopName: shopIdOrName });
}
const { updatedAt, ...others } = shop._doc;
res.status(200).json(others);
} catch (err) {
res.status(500).json("Shop not found!");
}
});
Client Side ShopPage.jsx:
const [shop, setShop] = useState({});
const shopName = useParams().shopName;
useEffect(() => {
const fetchShop = async () => {
const res = await axios.get(`/shops?shopName=${shopName}`);
setShop(res.data);
};
fetchShop();
}, [shopName]);
return (
<Box>
<Typography
className=""
mt="5px"
variant="h5"
fontWeight="medium"
align="left"
style={{ color: "black" }}>
{capitalizeFirstLetter(`${shop.shopName} `)}
</Typography>
</Box>
);
In my Client Side App.js
I'm using this route:
<Route path="/:shopName" element={<ShopPage />}>
</Route>
It supposed to show me the shop name, but instead it showing me "undefined", I don't know what i'm missing here.
CodePudding user response:
I can see that you are accepting the route on Backend is '/:shopname'
but from the frontend you are sending it like /shops?shopName=${shopName}
which is a query string .
you should send it like
axios.get(`${shopName`)
or if your route in backend is bound with path /shop/shopname
then you should send the request from frontend like this:
axios.get(`/shop/${shopName`)