Skip to content

Instantly share code, notes, and snippets.

@v-stickykeys
Created July 12, 2020 07:46
Show Gist options
  • Save v-stickykeys/f401662c1f44c1ed359c29160c719b68 to your computer and use it in GitHub Desktop.
Save v-stickykeys/f401662c1f44c1ed359c29160c719b68 to your computer and use it in GitHub Desktop.
// This is not clean and some of it needs to be deleted but hey, it works!
import React from "react";
import Box from "3box";
import Web3 from "web3";
function Test3Box() {
const [connectedToMM, setConnectedToMM] = React.useState(false);
const [account, setAccount] = React.useState("");
const [web3, setWeb3] = React.useState(null);
const [boxSyncDone, setBoxSyncDone] = React.useState(false);
const [boxWrites, setBoxWrites] = React.useState([]);
const [boxReads, setBoxReads] = React.useState(null);
const [inputKey, setInputKey] = React.useState("");
const [inputValue, setInputValue] = React.useState("");
React.useEffect(() => {
if (typeof window.ethereum !== "undefined") {
// console.log('MetaMask is installed!');
setConnectedToMM(true);
let web3Instance = new Web3(Web3.givenProvider);
setWeb3(web3Instance);
Box.create().then((box) => {
window.box = box;
});
}
}, []);
async function getAccount() {
const accounts = await web3.eth.getAccounts(console.log);
const account = accounts[0];
setAccount(account);
}
async function openBox() {
window.ethereum
.enable()
.then(async () => {
const ipfs = await Box.getIPFS();
console.log(ipfs);
window.box.auth([], { address: account, provider: window.ethereum });
window.box.onSyncDone(() => {
setBoxSyncDone(true);
});
})
.catch(console.error);
}
async function writeToBox() {
window.box.public
.set(inputKey, inputValue)
.then(() => {
const nextBoxWrites = [...boxWrites, [inputKey, inputValue]];
setBoxWrites(nextBoxWrites);
})
.catch(console.error);
}
async function readFromBox() {
const profile = await Box.getProfile(account);
setBoxReads(JSON.stringify(profile));
}
function handleInputKey(e) {
setInputKey(e.target.value);
}
function handleInputValue(e) {
setInputValue(e.target.value);
}
function renderWrites() {
return boxWrites.map((item) => {
return (
<div>
Key: {item[0]}, Value: {item[1]}
</div>
);
});
}
return (
<div>
<h1>3Box Test</h1>
{!connectedToMM && <div>Connecting...</div>}
{connectedToMM && (
<>
<button onClick={getAccount}>Get account!</button>
<div>Account: {account}</div>
{account && <button onClick={openBox}>Open box!</button>}
{boxSyncDone && (
<>
<div>Box sync is done!</div>
<input
type="text"
placeholder="key"
value={inputKey}
onChange={handleInputKey}
/>
<input
type="text"
placeholder="value"
value={inputValue}
onChange={handleInputValue}
/>
<button onClick={writeToBox}>Write to box</button>
{renderWrites()}
{boxReads}
<button onClick={readFromBox}>Read from box</button>
</>
)}
</>
)}
</div>
);
}
export default Test3Box;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment