Implementation in React

Running Syft.js in React is fairly simple. It's highly suggested you read the Introduction and Guide first if you haven't already.

const mySyft = new Syft({
verbose: true
});
class Playground extends Component {
constructor(props) {
super(props);
this.state = {
// Store syft related information
syftRunning: false,
syftLocation: 'ws://localhost:1112/',
// Track the tensors in React separately
tensors: [],
// For performing an operation we need to set some defaults
operation: 'add',
tensorA: '',
tensorB: '',
// And store the result
result: null
};
}
componentDidMount() {
mySyft.start(this.state.syftLocation);
const updateTensorsState = (tensors, isRemoved) => {
if (isRemoved) {
console.log('TENSOR REMOVED', tensors);
} else {
console.log('TENSOR ADDED', tensors);
}
const newState = isRemoved ? { tensors, result: null } : { tensors };
this.setState(newState, () => {
if (tensors.length >= 2) {
this.setState({
tensorA: tensors[0].id,
tensorB: tensors[1].id
});
} else {
this.setState({
tensorA: '',
tensorB: ''
});
}
});
};
mySyft.onTensorAdded(({ tensors }) => updateTensorsState(tensors, false));
mySyft.onTensorRemoved(({ tensors }) => updateTensorsState(tensors, true));
mySyft.onRunOperation(({ func, result }) => {
console.log('OPERATION RAN: ' + func, result);
this.setState({ result });
});
mySyft.onMessageReceived(data => {
console.log('MESSAGE RECEIVED', data);
});
mySyft.onMessageSent(data => {
console.log('MESSAGE SENT', data);
});
}
render() {
return <p>Syft.js is awesome - check your console!</p>;
}
}

You'll notice that this example heavily utilizes Event Handlers to tell us when any tensor is added, remove, or operated against, as well as when any message is received from or sent to PySyft. Of course, we can add a UI to manually add, remove, and operate against tensors... for this, we suggest you refer to this example.