Fetching latest data from Sanity database
11 replies
Last updated: Apr 10, 2023
H
Hi, I'm trying to get the latest information from my sanity database and I can see that it's updated in my desk, but my fetch just keeps getting old information. Is there anyway to only fetch the latest information?
const getUserCart = async (req, res) => { try { const currentUserId = req.userInfo.userId; const carts = await client.fetch( *[_type == "carts" && userId == $userId], { userId: currentUserId, force: true, } ); res.json(carts); } catch (error) { console.log({ message: "Failed to get user cart" }); } };
Apr 10, 2023, 3:36 PM
K
are you fetching from cdn?
Apr 10, 2023, 3:37 PM
H
I don't believe so, it's trying to fetch data being stored by this function:
and the data looks like this in my desk:
const updateCart = async (req, res) => { try { const cartInfo = req.body; const { cartItems, totalPrice, totalQuantities } = cartInfo; const currentUserId = req.userInfo.userId; // Fetch all carts that belong to the current user const carts = await client.fetch( `*[_type == "carts" && userId == $userId]`, { userId: currentUserId } ); // Loop through the carts and update each one for (const cart of carts) { const { _id } = cart; // Update the cart document with the new cart items, total price, and total quantities await client .patch(_id) .set({ cartItems, totalPrice, totalQuantities }) .commit(); } res.sendStatus(200); } catch (error) { console.log({ message: "error at updateCart" }); } };
"name": "Drizco Z-Watch", "price": 200, "quantity": 1, "slug": { "_type": "slug", "current": "drizco-z-watch" } }, { "_createdAt": "2023-03-31T19:21:36Z", "_id": "ab5f9754-5837-4c96-aae9-67cc1a8538c8", "_rev": "2Vh7m7t6FPDRFeGM5I3Esj", "_type": "product", "_updatedAt": "2023-03-31T19:21:36Z", "details": "Most affordable earbuds on the market", "image": [ { "_key": "ba88e67e8f6d", "_type": "image", "asset": { "_ref": "image-07fd4b12012f56f93ee9c5090a09754b4d8ee9dd-600x600-webp", "_type": "reference" } },
Apr 10, 2023, 3:42 PM
K
what's your client config look like
Apr 10, 2023, 3:43 PM
H
I am using a cdn to initially store the images though
Apr 10, 2023, 3:43 PM
K
does it have cdn: true ?
Apr 10, 2023, 3:43 PM
H
yes
Apr 10, 2023, 3:43 PM
H
const sanityClient = require("@sanity/client"); const client = sanityClient({ projectId: "k0utdl03", dataset: "production", apiVersion: "2022-03-10", useCdn: true, token: process.env.NEXT_PUBLIC_SANITY_TOKEN, }); module.exports = { client, };
Apr 10, 2023, 3:43 PM
K
change that to false and you should be good
Apr 10, 2023, 3:43 PM
K
content will be cached on cdn and doesn't get updated for ~10 minutes
Apr 10, 2023, 3:44 PM
K
good for production but not development
Apr 10, 2023, 3:45 PM
H
I see, thank you for the help
Apr 10, 2023, 3:46 PM
Sanity– build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.