How can I create live search using socket.io?
I use RethinkDB + Node + Express + Socket.io + Redux + React, I am listening to event (it is changefeed created using rethinkdb), which sends me lets say 10 items on client side and displaying them using react.
Now I want to create live search, which sends query to server, searches for results in DB, returns first 10 results and sends them to client with socket.io
// emit events for changes
r.table('stackoverflow_questions')
.changes({ includeInitial: true, squash: true })
.limit(10)
.run(connection)
.then(changefeedSocketEvents(socket, 'topic'))
-
// Socket.io events for changefeed
module.exports = function (socket, entityName) {
return function (rows) {
rows.each(function (err, row) {
if (err) { return console.log(err) } else if (row.new_val && !row.old_val) {
socket.emit(entityName + ':insert', row.new_val)
} else if (row.new_val && row.old_val) {
socket.emit(entityName + ':update', row.new_val)
} else if (row.old_val && !row.new_val) {
socket.emit(entityName + ':delete', { id: row.old_val.id })
}
})
}
}
I don't have Idea how you can achieve that using socket.io, do you have to create custom socket event listeners on the fly for every custom query? (It sounds ridiculous to me, I think, that there should be a simple way)
I found a solution, here is a bare minimum example:
// server.js
const express = require('express')
const app = express()
const http = require('http')
const server = http.Server(app)
const io = require('socket.io')(server)
app.use(express.static('client'))
io.on('connection', function(client){
setInterval(() => io.emit('found', 'dfasdfadsfasdfasdf'), 5000)
console.log('connected with socket: ' + client.id)
client.on('search', function (text) {
const data = Math.random()
io.emit('found', data + text)
})
client.on('disconnect', function(){})
})
app.get('/')
server.listen(3000)
-
<!- index.html ->
<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="./client.js"></script>
<title>socket-io-live-search</title>
</head>
<body>
<div id='search'>
<input type ='text' />
</div>
</body>
</html>
-
// client.js
var socket = io()
const loaded = () => {
const inputEl = document.querySelector('#search input')
inputEl.oninput = (e) => socket.emit('search', e.target.value)
}
socket.on('found', (data) => console.log('found: ' + data))
document.addEventListener('DOMContentLoaded', loaded, false)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With