-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Hello World
Let's create a simple Hello World app in 9 lines of HTML and JS code:
If you do not know how to code JS/HTML yet, check out the beginner's guide.
This editor has a live preview. Changes you make will update instantly.
::: {codepen: 'link', tab1: 'codemirror'} :::
<!DOCTYPE html>
<style>html, body, textarea { width: 100%; height: 100%; padding: 0; margin: 0; }</style>
<textarea id="paste" placeholder="paste here!"></textarea>
<script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script><script>
gun = Gun(['http://localhost:8765/gun', 'https://gun-manhattan.herokuapp.com/gun']);
copy = gun.get('test').get('paste');
paste.oninput = () => { copy.put(paste.value) };
copy.on((data) => { paste.value = data });
</script>
Try typing in your name, or saying "Hello World!". This app will copy&paste any text between computers. For reals! Try opening this page up in another tab or refreshing the page. In 9 lines of code we just built a global copy&paste app! How cool is that?
First we setup a small amount of HTML to make a full size text area for users to type into. Then we load GUN and connect to our local relay or some other peers. All peers, even your browser, help other peers find data and each other. This keeps things decentralized.
Next we ask gun
to get
some data. This could be anything, like "Mark's age", or the paste
record on the test
table. We can keep chaining these queries together to traverse any graph of data.
copy
is a chain reference to the data, it is not the value of the data yet.
Before we can read any data, we first must write to it on the reference. So we add an oninput
callback listener to the HTML paste
id. This fires with events any time the user inputs or changes a value. Now all we have to do is call put
to save data on that chain reference. GUN will now synchronize it to other peers online.
Finally, we want to listen to realtime updates on
the chain reference. Just like how we added a listener to the HTML, we can also add a listener to GUN. It gets called with data
which is the raw actual value we want, and we then update the paste
textarea with that value.
Whenever we refresh the page, .on(
will also get and merge the latest cached data.
- Figure out how to quickly find answers to your questions in the next step.
- Watch the 2 minute Crash Course?
- Hands-on learn answers to all your questions in THE INTERACTIVE TUTORIAL!