MCPcopy Create free account
hub / github.com/electric-sql/electric / Example

Function Example

examples/encryption/src/Example.tsx:87–167  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

85}
86
87export const Example = () => {
88 const [items, setItems] = useState<Item[]>()
89
90 const { data } = useShape<EncryptedItem>({
91 url: `${API_URL}/items`,
92 })
93
94 const rows = data !== undefined ? data : []
95
96 // There are more efficient ways of updating state than always decrypting
97 // all the items on any change but just to demonstate the decryption ...
98 useEffect(() => {
99 async function init() {
100 const items = await Promise.all(
101 rows.map(async (row) => await decrypt(row))
102 )
103
104 setItems(items)
105 }
106
107 init()
108 }, [rows])
109
110 /*
111 * Handle adding an item by creating the item data, encrypting it
112 * and sending it to the API
113 */
114 async function createItem(event: React.FormEvent) {
115 event.preventDefault()
116
117 const form = event.target as HTMLFormElement
118 const formData = new FormData(form)
119 const title = formData.get(`title`) as string
120
121 const id = crypto.randomUUID()
122 const item = {
123 id,
124 title,
125 }
126
127 const data = await encrypt(item)
128
129 const url = `${API_URL}/items`
130 const options = {
131 method: `POST`,
132 body: JSON.stringify(data),
133 headers: {
134 'Content-Type': `application/json`,
135 },
136 }
137
138 await fetch(url, options)
139
140 form.reset()
141 }
142
143 if (items === undefined) {
144 return <div>Loading...</div>

Callers

nothing calls this directly

Calls 3

useShapeFunction · 0.90
initFunction · 0.70
mapMethod · 0.45

Tested by

no test coverage detected