Last active
July 15, 2021 09:40
-
-
Save Mulperi/df0852e94c56185a7eaef35f1895bcfd to your computer and use it in GitHub Desktop.
Socket.io client with React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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