How to load a file and generate multiple objects in Sanity custom component

6 replies
Last updated: Jul 28, 2022
Hi! β˜•
I would like to load a file and generate several new objects based on its contents (depending on the size of the loaded file). I can already do this for one output object (based on
the tutorial ), but I don't know how to make it more flexible so that I can load any number of objects.
I will be very grateful for your tips
πŸ€—
Jul 25, 2022, 6:54 AM
Hello
user N
can you be more specific please?
Jul 26, 2022, 5:35 PM
I have a text file
test.txt
that has
x
lines, for example, for
x=5
it would be:

line 1
line 2
line 3
line 4
line 5
I want to load the
test.txt
file into Sanity in my custom component, and then I want to cut it into five
string
objects that will be dropped into an
array
.
I can load in the component, read the entire file and perform operations on its contents (already done). The problem occurs when I want to write those five lines into five different new objects in the
array
. So far, I have managed to save the entire contents of the
test.txt
file to a single
string
I defined earlier.
In summary, I would like to implement a component that has two fields:
-
file
-
array

When the
test.txt
is loaded into file, the contents are split into
x
objects (
strings
), each of which is added (and displayed in Sanity) to the
array
.
Jul 27, 2022, 6:43 AM
If you can do it with JS (or TS) you can do it with Sanity. You can us normal .toString() and spread methods for getting your lined into and array, each of your txt lines must have some kind of line break marker (
\r\n
as a encodeURIComponent I think), which you can use as a stop when converting them into a string each.And then you should follow setting up the tutorial till the end (patches into the other field, which would be the array).
Hope that helps (The person who wrote the tutorial is on
🌴 and so I can only tell you as much), but I am sure you will get it to work! πŸ™‚
Jul 27, 2022, 11:08 AM
Thank you for your reply!
This
test.txt
content I can already download and processed. This problem is a step further: I don't know how to create new objects for the array in my custom component.
Jul 27, 2022, 11:18 AM
Uf, I managed to do it! πŸ₯³ I think you gave me a lot of motivation with the words "_If you can do it with JS (or TS) you can do it with Sanity._" For which I am very grateful to you
user J

I will share my solution later
πŸ”₯
Jul 28, 2022, 7:44 AM
Very happy I could help and especially motivate you!!! πŸ™‚ Yes please share your code (we could think about adding it to the exchange on our website, so others can also find help through it!
Jul 28, 2022, 7:56 AM

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?