How to turn off the websocket after component unmounts - javascript

this is my code snippet bellow,
I am trying to close the websocket connection after component unmounts, I just totally dont know how to do it
I am using this useEffect inside the same component I am also using useref to count the mounted count of the component so that the websocket doesn't creates more that 1 instance at a time
const mountedCount = useRef(0);
useEffect(() => {
const handleWebsocket = () => {
mountedCount.current++;
const socketURL = 'socket url here'
const socket = new WebSocket(socketURL);
socket.onopen = () => {
console.log('socket open')
};
socket.onclose = (closeEvent) => {
if (closeEvent.wasClean) return;
timeout = setTimeout(() => {
handleWebsocket();
}, envVariables.webSocketReconnectionTimeout);
};
socket.onerror = () => {
console.log('error here')
};
socket.onmessage = (messageEvent) => {
console.log('got the message')
};
return socket;
};
if (mountedCount.current === 0) {
handleWebsocket();
}
return () => {
clearTimeout(timeout);
};
}, [
dispatch,
userData.userInformation,
wss.connectionStatus
]);

const mountedCount = useRef(0);
const [currentSocket,setCurrentSocket]=useState(null)
useEffect(() => {
const handleWebsocket = () => {
mountedCount.current++;
const socketURL = 'socket url here'
const socket = new WebSocket(socketURL);
socket.onopen = () => {
console.log('socket open')
};
socket.onclose = (closeEvent) => {
if (closeEvent.wasClean) return;
timeout = setTimeout(() => {
handleWebsocket();
}, envVariables.webSocketReconnectionTimeout);
};
socket.onerror = () => {
console.log('error here')
};
socket.onmessage = (messageEvent) => {
console.log('got the message')
};
return socket;
};
if (mountedCount.current === 0) {
setCurrentSocket(handleWebsocket());
}
return () => {
clearTimeout(timeout);
currentSocket?.close();
};
}, [
dispatch,
userData.userInformation,
wss.connectionStatus
]);

or you can declare socket variable in one upper scope:
const mountedCount = useRef(0);
useEffect(() => {
let socket
const handleWebsocket = () => {
mountedCount.current++;
const socketURL = 'socket url here'
socket = new WebSocket(socketURL);
socket.onopen = () => {
console.log('socket open')
};
socket.onclose = (closeEvent) => {
if (closeEvent.wasClean) return;
timeout = setTimeout(() => {
handleWebsocket();
}, envVariables.webSocketReconnectionTimeout);
};
socket.onerror = () => {
console.log('error here')
};
socket.onmessage = (messageEvent) => {
console.log('got the message')
};
return socket;
};
if (mountedCount.current === 0) {
handleWebsocket();
}
return () => {
clearTimeout(timeout);
socket.close()
};
}, [
dispatch,
userData.userInformation,
wss.connectionStatus
]);

Related

Message Unable to show automatically in reciever's side with Socket.io

I'm trying to send real time message with socket.io.
But the problem is that The reciever won't receive the message until i refresh the browser.
i'm getting all the data on the console but not in recievers end
I want to make it a real time message
Below are my codes
Messenger FrontEnd
// Context State
const { friends, setFriends, message, setMessage, authInfo } = useAuth();
const [currentFriend, setCurrentFriend] = useState("");
const [activeUser, setActiveUser] = useState([]);
const [newMessage, setNewMessage] = useState("");
const [socketMessage, setSocketMessage] = useState("");
const { updateNotification } = useNotification();
useEffect(() => {
socket.current = io("ws://localhost:9000");
socket.current.on("getMessage", (data) => {
setSocketMessage(data);
});
}, []);
useEffect(() => {
if (socketMessage && currentFriend) {
if (
socketMessage.senderId === currentFriend._id &&
socketMessage.receiverId === authInfo.profile.id
) {
console.log([...message, socketMessage]); // I'm confused on what to do here
}
}
setSocketMessage("");
}, [socketMessage]);
Socket.io Backend
let users = [];
const addUser = (userId, socketId, userInfo) => {
const checkUser = users.some((u) => u.userId === userId);
if (!checkUser) {
users.push({ userId, socketId, userInfo });
}
};
const userRemove = (socketId) => {
users = users.filter((u) => u.socketId !== socketId);
};
const findFriend = (id) => {
return users.find((u) => u.userId === id);
};
io.on("connection", (socket) => {
console.log("Socket Is Connecting...");
socket.on("addUser", (userId, userInfo) => {
addUser(userId, socket.id, userInfo);
io.emit("getUser", users);
});
socket.on("sendMessage", (data) => {
const user = findFriend(data.receiverId);
if (user !== undefined) {
socket.to(user.socketId).emit("getMessage", {
senderId: data.senderId,
senderName: data.senderName,
receiverId: data.receiverId,
createAt: data.time,
message: {
text: data.message.text,
image: data.message.image,
},
});
}
});

WebSockets server receives data but doesn't send back response

WebSocket doesn't send back a response despite the payLoad of the response is correct. The connection between front end and back end seems fine too. The boolean toggling inside the object array also works fine and does it's job. Any ideas why it isnt sending the JSON back to front end?
--------------------Front-end--------------------
const clientChangeVote = (c) => {
const payLoad = {
method: "changeVote",
clientId: gameData.clients[c].id,
gameId: gameData.id,
};
// voteValue: gameData.clients[c].voteReady,
ws.send(JSON.stringify(payLoad));
};
-----------------Back-end------------------------
if (result.method === "changeVote") {
const gameId = result.gameId;
const clientId = result.clientId;
games[gameId].clients
.filter((x) => x.id === clientId)
.forEach((vote) => (vote.voteReady = !vote.voteReady));
const updatedData = games[gameId].clients;
const payLoad = {
method: "changeVote",
updatedData: updatedData,
};
const game = games[gameId];
console.log(games);
game.clients.forEach((c) => {
console.log(payLoad);
c.connection.send(JSON.stringify(payLoad, getCircularReplacer()));
});
}
function getCircularReplacer() {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
}
-----------Inside the respone area. Im using React-----------
const [ws, setWs] = useState(new W3CWebSocket(URL));
useEffect(() => {
ws.onopen = () => {
console.log("Successful connection");
};
ws.onmessage = (message) => {
if (response.method === "changeVote") {
console.log("Vote received");
}
return () => {
ws.onclose = () => {
console.log("Connection closed");
setWs(new WebSocket(URL));
};
};
}, [ws.onmessage, ws.onopen, ws.onclose]);
Change ws.onmessage() :
ws.onmessage = (message) => {
let response = JSON.parse(message.data)
if (response.method === "changeVote") {
console.log("Vote received");
}
if not works add a comment.

WebRTC Data Channel Connection Fails as soon as i add media tracks to the connection

I have been trying to create a video group call application. It follows a mesh topology and the steps I follow are these:
When a client connects. A room is created if it is the first client or it broadcasts its socket id to all other clients in that room
When a client receives the socket id it sends it an offer and the cycle starts. A similar flow is followed for the other clients.
The problem is when I simply create data channels, it works fine but as soon as I start adding media Tracks, things break and even the data channel doesn't get connected. I'll attach the code below
import { io } from 'socket.io-client'
class RTConnection {
constructor() {
this.config = {
iceServers: [
{
urls: ["stun:stun.l.google.com:19302"]
}
]
}
this.connections = {}
this.videoElements = {}
this.ICEqueue = {}
}
init = async (roomId, videoElemRef) => {
this.roomId = roomId
this.videoElemRef = videoElemRef.current
let video = document.createElement('VIDEO')
this.myVideo = video
video.onloadedmetadata = e => video.play()
this.videoElemRef.appendChild(video)
const stream = await navigator.mediaDevices.getUserMedia({video: true, audio: false})
video.srcObject = stream
this.socket = io()
this.socket.emit("join-room", roomId)
this.socket.on('new-member', id => {
this.createOffer(id)
})
this.socket.on("offer", (id, offer) => {
this.acceptOffer(id, offer)
})
this.socket.on("new-ice-candidate", (id, candidate) => {
this.handleIceCandidate(id, candidate)
})
this.socket.on("answer", (id, answer) => {
this.acceptAnswer(id, answer)
})
}
acceptAnswer = async (id, answer) => {
const peerConnection = this.connections[id]
await peerConnection.setRemoteDescription(answer)
console.log("Answer Accepted")
}
handleIceCandidate = async (id, candidate) => {
if(!candidate) {
return
}
const peerConnection = this.connections[id]
if(peerConnection.remoteDescription) {
console.log("Setting Ice")
console.log(candidate)
await peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
} else {
if(id in this.ICEqueue) {
console.log("Storing Ice Candidates")
console.log(id)
this.ICEqueue[id].push(candidate)
} else {
this.ICEqueue[id] = []
}
}
}
hydrateIceCandidates = async (id) => {
const peerConnection = this.connections[id]
console.log("Hydrating Ice")
for(let i in this.ICEqueue[id]) {
const candidate = this.ICEqueue[id][i]
await peerConnection.addIceCandidate(candidate)
}
}
acceptOffer = async (id, offer) => {
const peerConnection = new RTCPeerConnection()
peerConnection.ondatachannel = e => {
console.log("Data Channel Received")
peerConnection.dc = e.channel
peerConnection.dc.onopen = e => console.log("Connected!!!!")
}
this.connections[id] = peerConnection
peerConnection.onicecandidate = e => {
this.socket.emit("new-ice-candidate", e.candidate)
}
peerConnection.ontrack = (e) => {
console.log("Received a track");
console.log(e.streams)
const video = document.createElement('VIDEO')
this.videoElemRef.appendChild(video)
video.onloadeddata = ev => {console.log("Meta Data Loaded") ; video.play()}
video.srcObject = e.streams[0]
}
const stream = this.myVideo.srcObject
console.log("Private Stream")
console.log(stream)
//await stream.getTracks().forEach(async track => peerConnection.addTrack(track, stream))
await peerConnection.setRemoteDescription(offer)
console.log("Remote Description Set")
const ans = await peerConnection.createAnswer()
console.log("Answer Created")
await peerConnection.setLocalDescription(ans)
console.log("Local Description Set")
await this.hydrateIceCandidates(id)
this.socket.emit("answer", id, ans)
}
createOffer = async (id) => {
const peerConnection = new RTCPeerConnection()
const stream = this.myVideo.srcObject
//stream.getTracks().forEach(track => peerConnection.addTrack(track, stream))
peerConnection.dc = peerConnection.createDataChannel("channel")
peerConnection.dc.onopen = e => {
console.log("Connected!!!")
}
this.connections[id] = peerConnection
peerConnection.ontrack = (e) => {
console.log("Received a track");
console.log(e.streams)
const video = document.createElement('VIDEO')
console.log("Video Element")
console.log(video)
this.videoElemRef.appendChild(video)
video.onloadedmetadata = ev => video.play()
video.srcObject = e.streams[0]
}
peerConnection.onicecandidate = (e) => {
this.socket.emit("new-ice-candidate", e.candidate)
}
const offer = await peerConnection.createOffer()
await peerConnection.setLocalDescription(offer)
console.log(peerConnection.localDescription)
this.socket.emit("offer", id, offer)
}
stopStream = (stream, elem) => {
stream.getTracks().forEach(track => {
track.stop()
})
this.videoElemRef.current.removeChild(elem)
}
cleanMedia = () => {
this.stopStream(this.videoEl.srcObject, this.videoEl)
for(let id in this.videoElements) {
this.stopStream(this.videoElements[id].srcObject, this.videoElements[id])
delete this.videoElements[id]
}
delete this.videoElements
}
leaveCall = () => {
for(let id in this.connections) {
this.connections[id].close()
delete this.connections[id]
}
delete this.connections
this.cleanMedia()
this.socket.disconnect()
}
}
export default RTConnection
Server-Side Code
const express = require('express')
const fs = require('fs')
const app = express()
const path = require('path')
const v4 = require('uuid').v4
const options = {
key: fs.readFileSync("key.pem"),
cert: fs.readFileSync("cert.pem")
}
const server = require('http').createServer(app)
const io = require('socket.io')(server)
const port = process.env.port || '5000'
app.set('view engine', 'ejs')
app.use("/",express.static(path.resolve(__dirname + '/public')))
app.get('/',(req, res) => {
res.render('home')
})
app.get('/room', (req,res) => {
const roomId = v4()
res.redirect(`/room/${roomId}`)
})
app.get('/room/:roomId',(req, res) => {
res.render('room', {roomId: req.params.roomId})
})
server.listen(port, () => {
console.log(`Starting server on ${port}`)
})
io.on("connection", socket => {
socket.on('join-room', (roomId) => {
socket.join(roomId)
socket.to(roomId).emit("new-member", socket.id)
socket.on("new-ice-candidate", (candidate) => {
socket.to(roomId).emit("new-ice-candidate", socket.id, candidate)
})
socket.on("offer", (id, offer) => {
socket.to(id).emit("offer", socket.id, offer)
})
socket.on("answer", (id, answer) => {
socket.to(id).emit("answer", socket.id, answer)
})
socket.on("disconnecting", () => {
for(let room of socket.rooms) {
socket.to(room).emit("leaveCall", socket.id)
}
})
})
})

can't do video chat with peer.js

I'm following this website to make a video call in react.
I slightly changed the code in connection.js for my pure javascript project, but other files are same as the tutorial.
Here is my connection.js
import openSocket from 'socket.io-client';
import Peer from 'peerjs';
let socketInstance = null;
let peers = {};
const initializePeerConnection = () => {
return new Peer('', {
host: 'localhost',
port: 9000,
secure: false //secure=true is https and wss. secure=false is http and ws
});
//return new Peer()
}
const initializeSocketConnection = () => {
const socket = openSocket('http://localhost:5000');
return socket
}
class Connection {
videoContainer = {};
message = [];
settings;
streaming = false;
myPeer;
socket;
myID = '';
constructor(settings) {
this.settings = settings;
this.myPeer = initializePeerConnection();
this.socket = initializeSocketConnection();
this.initializeSocketEvents();
this.initializePeersEvents();
}
initializeSocketEvents = () => {
this.socket.on('connect', () => {
console.log('socket connected');
});
this.socket.on('user-disconnected', (userID) => {
console.log('user disconnected-- closing peers', userID);
peers[userID] && peers[userID].close();
this.removeVideo(userID);
});
this.socket.on('disconnect', () => {
console.log('socket disconnected --');
});
this.socket.on('error', (err) => {
console.log('socket error --', err);
});
}
initializePeersEvents = () => {
this.myPeer.on('open', (id) => {
this.myID = id;
const roomID = window.location.pathname.split('/')[2];
const userData = {
userID: id, roomID
}
console.log('mydata::', userData)
this.socket.emit('join-room', userData);
this.setNavigatorToStream();
});
this.myPeer.on('error', (err) => {
console.log('peer connection error', err);
this.myPeer.reconnect();
})
}
setNavigatorToStream = () => {
this.getVideoAudioStream().then((stream) => {
if (stream) {
this.streaming = true;
this.createVideo({ id: this.myID, stream });
this.setPeersListeners(stream);
this.newUserConnection(stream);
}
})
}
getVideoAudioStream = (video=true, audio=true) => {
let quality = this.settings.params?.quality;
if (quality) quality = parseInt(quality);
const myNavigator = navigator.mediaDevices.getUserMedia ||
navigator.mediaDevices.webkitGetUserMedia ||
navigator.mediaDevices.mozGetUserMedia ||
navigator.mediaDevices.msGetUserMedia;
return myNavigator({
video: video ? {
frameRate: quality ? quality : 12,
noiseSuppression: true,
width: {min: 640, ideal: 1280, max: 1920},
height: {min: 480, ideal: 720, max: 1080}
} : false,
audio: audio,
});
}
createVideo = (createObj) => {
console.log('video created')
if (!this.videoContainer[createObj.id]) {
this.videoContainer[createObj.id] = {
...createObj,
};
const roomContainer = document.getElementById('room-container');
const videoContainer = document.createElement('div');
const video = document.createElement('video');
video.srcObject = this.videoContainer[createObj.id].stream;
video.id = createObj.id;
video.autoplay = true;
if (this.myID === createObj.id) {
video.muted = true;
video.className = 'my_video'
}
videoContainer.appendChild(video)
roomContainer.append(videoContainer);
} else {
const video = document.getElementById(createObj.id)
video.srcObject = createObj.stream
}
}
setPeersListeners = (stream) => {
//stream is my stream
this.myPeer.on('call', function(call) {
console.log('answered!!')
call.answer(stream);
call.on('stream', (userVideoStream) => {
console.log('user stream data', userVideoStream)
this.createVideo({ id: call.metadata.id, stream: userVideoStream });
});
call.on('close', () => {
console.log('closing peers listeners', call.metadata.id);
this.removeVideo(call.metadata.id);
});
call.on('error', () => {
console.log('peer error ------');
this.removeVideo(call.metadata.id);
});
peers[call.metadata.id] = call;
});
}
newUserConnection = (stream) => {
//stream is my stream
this.socket.on('new-user-connect', (userData) => {
this.connectToNewUser(userData, stream);
});
}
connectToNewUser(userData, stream) {
console.log('connectTonewUser is called')
const { userID } = userData;
const call = this.myPeer.call(userID, stream, { metadata: { id: this.myID }} );
console.log('your data:: new user connected', userData)
call.on('stream', (userVideoStream) => {
//userVideoStream is your stream
console.log('your stream::', userVideoStream)
this.createVideo({ id: userID, stream: userVideoStream, userData });
});
call.on('close', () => {
console.log('closing new user', userID);
this.removeVideo(userID);
});
call.on('error', () => {
console.log('peer error ------')
this.removeVideo(userID);
})
peers[userID] = call;
}
removeVideo = (id) => {
delete this.videoContainer[id];
const video = document.getElementById(id);
if (video) video.remove();
}
destroyConnection = () => {
const myMediaTracks = this.videoContainer[this.myID]?.stream.getTracks();
myMediaTracks?.forEach((track) => {
track.stop();
})
socketInstance?.socket.disconnect();
this.myPeer.destroy();
}
}
export default function createSocketConnectionInstance(settings={}) {
return socketInstance = new Connection(settings);
}
It is confirmed that both two clients are connected to peer.js and the sockets are also connected.
However, after I called in connectToNewUser, it seems to not answer in setPeersListeners.
I think the shape of video call function is quite same as peerjs doc
Do you have any ideas why it doesn't work?
Thank you :)
It worked when I removed all arguments somehow.
used to be
const initializePeerConnection = () => {
return new Peer('', {
host: 'localhost',
port: 9000,
secure: false //secure=true is https and wss. secure=false is http and ws
});
}
and in terminal
peerjs -p 9000
👇
this is working correctly
const initializePeerConnection = () => {
return new Peer()
}
you don't have to exectute peerjs in terminal

IndexedDB takes time to initialize outer scope variable db which is needed in another function

I am opening a database using indexedDB using javascript for keeping a diary entry. I am doing three things with the database: display all entry, add entry, and remove entry.
It fails when it tries to create a transaction because 'db' is 'undefined.' I was expecting db to be defined by the time the code tries to create a transaction.
Error is caused at the line with code:
const getObjectStore = (storeName, mode) => {
console.log('db: ', db);
const tx = db.transaction(storeName, mode); // error is thrown because db is undefined
return tx.objectStore(storeName);
};
I tried to put console.log at different places to see what is wrong. I found that db takes time before it gets defined by an onsuccess response or onupgradeneeded response. I don't see any other way to define db before it is used. Can you show me how I can assure myself for the assignment of db before it is used?
Outputs:
> adding something in the diary
> db from getObjectStore: undefined
> Uncaught TypeError: Cannot read property 'transaction' of undefined
at getObjectStore (script.js:35)
at Object.setAnEntry [as add] (script.js:62)
at script.js:81
at script.js:215
getObjectStore # script.js:35
setAnEntry # script.js:62
(anonymous) # script.js:81
(anonymous) # script.js:215
> there is indexeddb!
> db: IDBDatabase {name: "medDiary", version: 1, objectStoreNames: DOMStringList, onabort: null, onclose: null, …}
All the code i am working with:
// DATABASE FOR THE DIARY
const Dairy = (() => {
if (window.indexedDB) {
let db;
const DB_NAME = 'Dairy';
const DB_VERSION = 1;
const DB_STORE_NAME = 'diaries';
const request = window.indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => {
console.log('Error requesting to open database permission denied.');
};
request.onsuccess = (event) => {
console.log('there is indexeddb!');
db = event.target.result;
console.log('db: ', db);
db.onerror = (evt) => {
console.error(`Database error: ${evt.target.errorCode}`);
};
};
request.onupgradeneeded = (event) => {
db = request.result;
const store = event.currentTarget.result.createObjectStore(DB_STORE_NAME, { keyPath: 'date' });
store.createIndex('subject', 'subject', { unique: false });
store.createIndex('date', 'date', { unique: true });
store.createIndex('description', 'description', { unique: false });
};
const getObjectStore = (storeName, mode) => {
console.log('db from getObjectStore: ', db);
const tx = db.transaction(storeName, mode);
return tx.objectStore(storeName);
};
const getAllEntries = () => new Promise((resolve) => {
const result = [];
const store = getObjectStore(DB_STORE_NAME, 'readonly');
const req = store.openCursor();
req.onsuccess = (evt) => {
const cursor = evt.target.result;
if (cursor) {
const retrive = store.get(cursor.key);
retrive.onsuccess = function (evt) {
const value = evt.target.result;
result.append(value);
};
cursor.continue();
} else {
console.log('No more entries');
resolve(result);
}
};
});
const setAnEntry = (value) => {
const store = getObjectStore(DB_STORE_NAME, 'readwrite');
store.put(value);
};
const removeAnEntry = (value) => {
const store = getObjectStore(DB_STORE_NAME, 'readwrite');
store.remove(value);
};
return {
all: getAllEntries,
add: setAnEntry,
remove: removeAnEntry,
};
}
alert("Your browser doesn't support a stable version of IndexedDB. Dairy related features will not be available.");
return {};
})();
console.log('adding something in the diary');
console.log('... ', Dairy.add({ subject: 'hello', description: 'bluh bluh', date: Date() }));
console.log('show all: ', Dairy.all());
You can use a promise to open the DB:
let promise = new Promise(function(resolve, reject)
{
//check for support
if (!('indexedDB' in window)) {
//console.log('This browser doesn\'t support IndexedDB');
reject("indexedDB not supported");
}
var request = indexedDB.open(dbName, dbVersion);
request.onerror = function (event) {
reject("Error opening DB");
};
request.onsuccess = function (event) {
console.log("opened!");
db = request.result;
resolve(true);
};
});
And then you can use:
promise
.then(
result => {
your stuff here sine the DB is now open!!
},
error => console.log(error)
)
The parameter passed to resolve will be available as 'result'.
To use in your module format:
Add init function:
async function init()
{
let promise = new Promise(function(resolve, reject)
{
//check for support
if (!('indexedDB' in window)) {
//console.log('This browser doesn\'t support IndexedDB');
reject("indexedDB not supported");
}
var request = indexedDB.open(dbName, dbVersion);
request.onerror = function (event) {
reject("Error opening DB");
};
request.onsuccess = function (event) {
console.log("opened!");
db = request.result;
resolve(true);
};
});
let result = await promise;
}
Your module rewritten:
const Dairy = (() => {
if (window.indexedDB)
{
let db;
const DB_NAME = 'Dairy';
const DB_VERSION = 1;
const DB_STORE_NAME = 'diaries';
async function init()
{
let promise = new Promise(function(resolve, reject)
{
const request = window.indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => {
reject('Error requesting to open database permission denied.');
};
request.onsuccess = (event) => {
console.log('there is indexeddb!');
db = event.target.result;
console.log('db: ', db);
db.onerror = (evt) => {
reject("Database error: ${evt.target.errorCode}");
};
resolve(true);
};
request.onupgradeneeded = (event) => {
db = request.result;
const store = event.currentTarget.result.createObjectStore(DB_STORE_NAME, { keyPath: 'date' });
store.createIndex('subject', 'subject', { unique: false });
store.createIndex('date', 'date', { unique: true });
store.createIndex('description', 'description', { unique: false });
};
});
return promise;
}
const getObjectStore = (storeName, mode) => {
console.log('db from getObjectStore: ', db);
const tx = db.transaction(storeName, mode);
return tx.objectStore(storeName);
};
const getAllEntries = () => new Promise((resolve) => {
const result = [];
const store = getObjectStore(DB_STORE_NAME, 'readonly');
const req = store.openCursor();
req.onsuccess = (evt) => {
const cursor = evt.target.result;
if (cursor) {
const retrive = store.get(cursor.key);
retrive.onsuccess = function (evt) {
const value = evt.target.result;
result.append(value);
};
cursor.continue();
} else {
console.log('No more entries');
resolve(result);
}
};
});
const setAnEntry = (value) => {
const store = getObjectStore(DB_STORE_NAME, 'readwrite');
store.put(value);
};
const removeAnEntry = (value) => {
const store = getObjectStore(DB_STORE_NAME, 'readwrite');
store.remove(value);
};
return {
all: getAllEntries,
add: setAnEntry,
remove: removeAnEntry,
init: init
};
}
alert("Your browser doesn't support a stable version of IndexedDB. Dairy related features will not be available.");
return {};
})();
Dairy.init()
.then(
result => {
console.log('adding something in the diary');
console.log('... ', Dairy.add({ subject: 'hello', description: 'bluh bluh', date: Date() }));
console.log('show all: ', Dairy.all());
},
error => console.log(error)
);

Categories