use-publish-post-store.ts
1 import { PublishCommentOptions } from '@plebbit/plebbit-react-hooks'; 2 import { create } from 'zustand'; 3 import { alertChallengeVerificationFailed } from '../lib/utils/challenge-utils'; 4 import useChallengesStore from './use-challenges-store'; 5 6 type SubmitState = { 7 author?: any | undefined; 8 displayName?: string | undefined; 9 signer?: any | undefined; 10 subplebbitAddress: string | undefined; 11 title: string | undefined; 12 content: string | undefined; 13 link: string | undefined; 14 spoiler: boolean | undefined; 15 publishCommentOptions: PublishCommentOptions; 16 setPublishPostStore: (data: Partial<SubmitState>) => void; 17 resetPublishPostStore: () => void; 18 }; 19 20 const { addChallenge } = useChallengesStore.getState(); 21 22 const usePublishPostStore = create<SubmitState>((set) => ({ 23 author: undefined, 24 displayName: undefined, 25 signer: undefined, 26 subplebbitAddress: undefined, 27 title: undefined, 28 content: undefined, 29 link: undefined, 30 spoiler: undefined, 31 publishCommentOptions: {}, 32 setPublishPostStore: ({ author, displayName, signer, subplebbitAddress, title, content, link, spoiler }) => 33 set((state) => { 34 const nextState = { ...state }; 35 if (author !== undefined) nextState.author = author; 36 if (displayName !== undefined) nextState.displayName = displayName; 37 if (signer !== undefined) nextState.signer = signer; 38 if (subplebbitAddress !== undefined) nextState.subplebbitAddress = subplebbitAddress; 39 if (title !== undefined) nextState.title = title || undefined; 40 if (content !== undefined) nextState.content = content || undefined; 41 if (link !== undefined) nextState.link = link || undefined; 42 if (spoiler !== undefined) nextState.spoiler = spoiler || undefined; 43 44 const publishCommentOptions: PublishCommentOptions = { 45 subplebbitAddress: nextState.subplebbitAddress, 46 title: nextState.title, 47 content: nextState.content, 48 link: nextState.link, 49 spoiler: nextState.spoiler, 50 onChallenge: (...args: any) => addChallenge(args), 51 onChallengeVerification: alertChallengeVerificationFailed, 52 onError: (error: Error) => { 53 console.error(error); 54 alert(error.message); 55 }, 56 }; 57 58 if (nextState.signer) { 59 publishCommentOptions.signer = nextState.signer; 60 } 61 62 if (nextState.author || nextState.displayName) { 63 publishCommentOptions.author = { 64 ...nextState.author, 65 displayName: nextState.displayName, 66 }; 67 } 68 69 nextState.publishCommentOptions = publishCommentOptions; 70 return nextState; 71 }), 72 resetPublishPostStore: () => 73 set({ 74 author: undefined, 75 displayName: undefined, 76 signer: undefined, 77 subplebbitAddress: undefined, 78 title: undefined, 79 content: undefined, 80 link: undefined, 81 spoiler: undefined, 82 publishCommentOptions: {}, 83 }), 84 })); 85 86 export default usePublishPostStore;