grungnet/src/App.js

106 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-03-15 05:04:30 +00:00
import React, { useEffect, useState, useRef } from "react";
import Peer from "peerjs";
2020-03-15 06:50:56 +00:00
import {
ThemeProvider,
Box,
Heading,
Text,
Label,
Input,
Button
} from "theme-ui";
import theme from "./theme.js";
2020-03-15 05:04:30 +00:00
function App() {
const [id, setId] = useState("");
const peer = useRef(null);
useEffect(() => {
peer.current = new Peer();
}, []);
useEffect(() => {
function handleOpen(id) {
console.log("My peer ID is: " + id);
setId(id);
}
function handleConnection(connection) {
connection.on("open", () => {
2020-03-15 07:39:21 +00:00
if (imgRef.current) {
connection.send(imgRef.current);
}
2020-03-15 05:04:30 +00:00
});
}
peer.current.on("open", handleOpen);
peer.current.on("connection", handleConnection);
return () => {
peer.current.removeListener("open", handleOpen);
peer.current.removeListener("connection", handleConnection);
};
}, [id]);
const [connectId, setConnectId] = useState("");
const connectToId = () => {
const connection = peer.current.connect(connectId);
connection.on("open", () => {
connection.on("data", data => {
2020-03-15 07:39:21 +00:00
const blob = new Blob([data]);
imgRef.current = blob;
setImgSrc(URL.createObjectURL(imgRef.current));
2020-03-15 05:04:30 +00:00
});
});
};
2020-03-15 07:39:21 +00:00
const [imgSrc, setImgSrc] = useState("");
const imgRef = useRef(null);
const loadImage = e => {
imgRef.current = e.target.files[0];
setImgSrc(URL.createObjectURL(imgRef.current));
};
2020-03-15 05:04:30 +00:00
return (
2020-03-15 06:50:56 +00:00
<ThemeProvider theme={theme}>
<Box width={256}>
<Heading as="h3">Your ID</Heading>
<Text>{id}</Text>
2020-03-15 07:39:21 +00:00
<Box>
<img src={imgSrc} />
<Label htmlFor="image">Image</Label>
<Input
type="file"
accept="image/*"
name="image"
id="file"
onChange={loadImage}
/>
</Box>
2020-03-15 06:50:56 +00:00
<Box
as="form"
width={1 / 2}
onSubmit={e => {
e.preventDefault();
connectToId();
}}
py={3}
>
<Label htmlFor="connectId">Connect to</Label>
<Input
id="connectId"
name="connectId"
value={connectId}
onChange={e => setConnectId(e.target.value)}
/>
<Button>Connect</Button>
</Box>
</Box>
</ThemeProvider>
2020-03-15 05:04:30 +00:00
);
}
export default App;