From 556b3082309f663bcde895fbefc78ff5bfaabd3b Mon Sep 17 00:00:00 2001 From: Apostolof Date: Sun, 8 Nov 2020 11:49:30 +0200 Subject: [PATCH] Init orbit peer replication --- .../TopicList/TopicListRow/index.jsx | 43 +++++++++++++------ 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/packages/concordia-app/src/components/TopicList/TopicListRow/index.jsx b/packages/concordia-app/src/components/TopicList/TopicListRow/index.jsx index b4bc448..cc64284 100644 --- a/packages/concordia-app/src/components/TopicList/TopicListRow/index.jsx +++ b/packages/concordia-app/src/components/TopicList/TopicListRow/index.jsx @@ -1,24 +1,41 @@ -import React, { useContext, useMemo } from 'react'; +import React, { useContext, useEffect, useState } from 'react'; import { List } from 'semantic-ui-react'; import PropTypes from 'prop-types'; +import { useSelector } from 'react-redux'; import AppContext from '../../AppContext'; const TopicListRow = (props) => { const { topicData, topicId } = props; + const { breeze: { orbit } } = useContext(AppContext.Context); + const [topicSubject, setTopicSubject] = useState(); + const userAddress = useSelector((state) => state.user.address); - const { - breeze: { - orbit: { - stores, - }, - }, - } = useContext(AppContext.Context); + useEffect(() => { + if (userAddress === topicData.userAddress) { + const topicsDb = Object.values(orbit.stores).find((store) => store.dbname === 'topics'); - const topicSubject = useMemo(() => { - const topicsDb = Object.values(stores).find((store) => store.dbname === 'topics'); + setTopicSubject(topicsDb.get(topicId)); + return; + } - return topicsDb.get(topicId); - }, [stores, topicId]); + // TODO: this is not correct, each TopicListRow inside the TopicList overrides the on.replicated callback. As a + // result, for the topics of each user, only the callback of the last TopicListRow in the list survives and gets + // executed. Moving these calls up on the TopicList helps with this issue but introduces other problems. + orbit + .determineAddress('topics', 'keyvalue', { accessController: { write: [topicData.userAddress] } }) + .then((ipfsMultihash) => { + const peerDbAddress = `/orbitdb/${ipfsMultihash.root}/topics`; + + return orbit.keyvalue(peerDbAddress) + .then((keyValueStore) => { + keyValueStore.events.on('replicated', () => { + setTopicSubject(keyValueStore.get(topicId)); + }); + }) + .catch((error) => console.error(`Error opening a peer's db: ${error}`)); + }) + .catch((error) => console.error(`Error opening a peer's db: ${error}`)); + }, [orbit, topicData.userAddress, topicId, userAddress]); return ( <> @@ -40,7 +57,7 @@ const TopicListRow = (props) => { const TopicData = PropTypes.PropTypes.shape({ userAddress: PropTypes.string.isRequired, username: PropTypes.string.isRequired, - timestamp: PropTypes.string.isRequired, + timestamp: PropTypes.number.isRequired, numberOfReplies: PropTypes.number.isRequired, });