useProposalSubscription.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { useState, useEffect } from 'react';
  2. import { useTransport } from '../';
  3. import { ProposalId } from '@joystream/types/proposals';
  4. import { ParsedProposal } from '@polkadot/joy-utils/types/proposals';
  5. // Take advantage of polkadot api subscriptions to re-fetch proposal data and votes
  6. // each time there is some runtime change in the proposal
  7. const useProposalSubscription = (id: ProposalId) => {
  8. const transport = useTransport();
  9. // State holding current proposal data
  10. const [data, setData] = useState<ParsedProposal | null>(null);
  11. const [error, setError] = useState<any>(null);
  12. const [loading, setLoading] = useState<boolean>(true);
  13. useEffect(() => {
  14. // onMount...
  15. let unmounted = false;
  16. let unsubscribeProposal: (() => void) | undefined;
  17. const refreshProposalData = () => {
  18. transport.proposals.proposalById(id)
  19. .then(newData => {
  20. if (!unmounted) {
  21. setData(newData);
  22. setLoading(false);
  23. }
  24. })
  25. .catch(error => {
  26. if (!unmounted) {
  27. setError(error);
  28. setLoading(false);
  29. }
  30. });
  31. };
  32. // Create the subscription
  33. transport.proposals.subscribeProposal(id, refreshProposalData)
  34. .then(unsubscribe => {
  35. if (!unmounted) {
  36. unsubscribeProposal = unsubscribe;
  37. } else {
  38. unsubscribe(); // If already unmounted - unsubscribe immedietally!
  39. }
  40. });
  41. return () => {
  42. // onUnmount...
  43. // Clean the subscription
  44. unmounted = true;
  45. if (unsubscribeProposal) {
  46. unsubscribeProposal();
  47. }
  48. };
  49. }, []);
  50. return { data, error, loading };
  51. };
  52. export default useProposalSubscription;