arnodorian067
arnodorian067

Reputation: 37

Uploading image to sanity io in react native

I have a array of objects in sanity io and each object is like this:

{
      name: "savedFaces",
      title: "Saved Faces",
      type: "array",
      of: [
        {
          name: "savedFace",
          title: "Saved Face",
          type: "object",
          fields: [
            {
              name: "title",
              title: "Title",
              type: "string",
            },
            {
              name: "notes",
              title: "Notes",
              type: "string",
            },
            {
              name: "savedDate",
              title: "Saved Date",
              type: "string",
            },
            {
              name: "image",
              title: "Image",
              type: "image",
            },
          ],
        },
      ],
    },

and I want to upload an image from the app to sanity, I convert the image URI to base64:

`data:image/jpg;base64,${uriToBase64.base64}`

but when I send the data sanity shows an error saying the type of the sent data is string.

and this is the request code:

const mutations = [
    {
      patch: {
        id: 'd596fa17-9816-4463-ae81-85a6f34bc414',
        set: {
          after: 'savedFaces[-1]',
          items: [
            {
              _key: Date.now().toString(),
              title: savedFace.title,
              notes: savedFace.description,
              savedDate: savedFace.savedDate,
              image: `data:image/jpg;base64,${uriToBase64.base64}`
            }
          ]
        }
      }
    }
  ];

  await axios.post(
    `https://${PROJECT_ID}.api.sanity.io/v2021-06-07/data/mutate/${DATASET}`,
    JSON.stringify({ mutations }),
    {
      headers: {
        'content-type': 'application/json',
        Authorization: `Bearer ${API_TOKEN}`
      }
    }
  );

Upvotes: 0

Views: 662

Answers (1)

user15378778
user15378778

Reputation: 36

Try this 😊

const img = await fetch(result.uri);
      const bytes = await img.blob();
      sanityClient.assets.upload('image', bytes, { filename: 'image' }).then((imageAsset) => {
        const doc: any = {
          _type: '...',
          name: '....',
          ...
        };

        sanityClient.create(doc).then((response) => {
          console.log(response);
          return sanityClient
            .patch(response._id)
            .set({
              image: {
                _type: 'image',
                asset: {
                  _type: 'reference',
                  _ref: imageAsset._id,
                },
              },
            })
            .commit();
        });

      });
    }

<!-- end 

<!-- begin snippet: js hide: false console: true babel: false -->

snippet -->

Upvotes: 2

Related Questions