Skip to content

Instantly share code, notes, and snippets.

@Mulperi
Last active July 15, 2021 09:40
Show Gist options
  • Save Mulperi/df0852e94c56185a7eaef35f1895bcfd to your computer and use it in GitHub Desktop.
Save Mulperi/df0852e94c56185a7eaef35f1895bcfd to your computer and use it in GitHub Desktop.
Socket.io client with React
import React, { useState } from 'react';
import FeatureHeading from '../components/FeatureHeading';
import { io } from 'socket.io-client';
import { useEffect } from 'react';
export default function LiveFeedView() {
/** Create socket conenction. */
const [live, setLive] = useState(null);
useEffect(() => {
const socket = io('ws://localhost:5000/livefeed');
socket.on('connect', function () {
console.log('CONNECTED');
});
socket.on('disconnect', function () {
console.log('DISCONNECTED');
});
socket.on('update', function (payload: any) {
setLive(payload.src);
});
/** On component destroy. */
return () => {
socket.close();
};
}, []);
return (
<React.Fragment>
<FeatureHeading
title="Live feed"
description="Live feed description text"
/>
{live && <img src={`http://localhost:5000/${live}`} alt="live feed" />}
</React.Fragment>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment