variant with preact instead of vanilla js

with-preact
Antonio De Lucreziis 2 years ago
parent 6e98443bb9
commit a1502eb2da

@ -6,11 +6,7 @@
</head> </head>
<body> <body>
<h1>GDG Counter Website</h1> <h1>GDG Counter Website</h1>
<div class="app"> <div id="app"></div>
<div id="counter-value">???</div> <script type="module" src="/src/main.jsx"></script>
<button id="btn-decrement">Decrementa</button>
<button id="btn-increment">Incrementa</button>
</div>
<script type="module" src="/src/main.js"></script>
</body> </body>
</html> </html>

1423
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -6,6 +6,10 @@
"build": "vite build" "build": "vite build"
}, },
"devDependencies": { "devDependencies": {
"@preact/preset-vite": "^2.5.0",
"vite": "^3.2.3" "vite": "^3.2.3"
},
"dependencies": {
"preact": "^10.13.0"
} }
} }

@ -1,27 +0,0 @@
const counterElement = document.querySelector('#counter-value')
const incrementButton = document.querySelector('#btn-increment')
const decrementButton = document.querySelector('#btn-decrement')
function updateCounter(value) {
counterElement.textContent = `Counter: ${value}`
}
incrementButton.addEventListener('click', async () => {
const res = await fetch('/api/increment', { method: 'POST' })
const data = await res.json()
updateCounter(data)
})
decrementButton.addEventListener('click', async () => {
const res = await fetch('/api/decrement', { method: 'POST' })
const data = await res.json()
updateCounter(data)
})
async function main() {
const res = await fetch('/api/value')
const data = await res.json()
updateCounter(data)
}
main()

@ -0,0 +1,38 @@
import { render } from 'preact'
import { useState, useEffect } from 'preact/hooks'
const App = ({}) => {
const [counter, setCounter] = useState(0)
useEffect(() => {
fetch('/api/value')
.then(res => res.json())
.then(count => setCounter(count))
}, [])
return (
<>
<div>{counter}</div>
<button
onClick={() => {
fetch('/api/decrement', { method: 'POST' })
.then(res => res.json())
.then(count => setCounter(count))
}}
>
Decrementa
</button>
<button
onClick={() => {
fetch('/api/increment', { method: 'POST' })
.then(res => res.json())
.then(count => setCounter(count))
}}
>
Incrementa
</button>
</>
)
}
render(<App />, document.querySelector('#app'))

@ -1,3 +1,4 @@
import preactPlugin from '@preact/preset-vite'
import { defineConfig } from 'vite' import { defineConfig } from 'vite'
export default defineConfig({ export default defineConfig({
@ -7,4 +8,5 @@ export default defineConfig({
'/api': 'http://localhost:4000/', '/api': 'http://localhost:4000/',
}, },
}, },
plugins: [preactPlugin()],
}) })

Loading…
Cancel
Save