Error fetching Instagram posts due to incorrect API usage

1 replies
Last updated: May 29, 2023
hey, in my StudioNavbar.tsx I want to fetch posts from instagram, it previously worked when I only fetch and inport new posts, but now I'm trying to update the media URL of existing ones at the same time. here's my function:const fetchInstagramPosts = async () => {
const existingPosts = await client.fetch(

      *[ _type == "instagramPost" ] {
        _id,
        instagramId
      }
    
);
try {
const url = `
https://graph.instagram.com/me/media?fields=id,media_url,timestamp&access_token=${INSTAGRAM_KEY} `; const res = await fetch(url);
const data = await res.json();
if (!data || !data.data) {
console.error(
"Error: Instagram API returned an unexpected response",
data
);
return;
}

// Create a transaction for creating or updating the documents
const transaction = client.transaction();

for (const post of data.data) {
const existingPost = existingPosts.find(
(p: any) => p.instagramId === post.id
);

if (existingPost) {
// Update the existing post's mediaUrl
transaction.patch(existingPost._id).set({
mediaUrl: post.media_url,
timestamp: post.timestamp,
});
} else {
// Create a new document
const newPost = {
_type: "instagramPost",
instagramId: post.id,
mediaUrl: post.media_url,
timestamp: post.timestamp,
articleLink: "
https://www.nordkurier.de/ ", // set a default value };

transaction.create(newPost);
}
}

// Commit the transaction
await transaction.commit();
} catch (error) {
console.error("Error fetching Instagram posts", error);
}
};

But I receive this error:
Error fetching Instagram posts TypeError: transaction.patch(...).set is not a function

Can someone help me?
May 29, 2023, 6:59 PM
Hi Max. That doesn’t appear to be the right API for
transaction()
. Could you please try changing this:

transaction.patch(existingPost._id).set({
  mediaUrl: post.media_url,
  timestamp: post.timestamp,
});
to this:


transaction.patch(client.patch(existingPost._id).set({
  mediaUrl: post.media_url,
  timestamp: post.timestamp,
}));
Which, if we remove the abstraction, is effectively this:


client
  .transaction()
  .patch(
    client
      .patch(existingPost._id)
      .set({
        mediaUrl: post.media_url,
        timestamp: post.timestamp,
      })
  )
  .commit() // I'm assuming this happens later in your code and works
May 29, 2023, 7:41 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.

Was this answer helpful?