77ea27f5f5
Co-authored-by: Nahiyan Khan <nahiyan@squareup.com> Co-authored-by: Taylor Ho <taylorkmho@gmail.com> Co-authored-by: Lily Delalande <119957291+lily-de@users.noreply.github.com> Co-authored-by: Spence <spencrmartin@gmail.com> Co-authored-by: spencrmartin <spencermartin@squareup.com> Co-authored-by: Judson Stephenson <Jud@users.noreply.github.com> Co-authored-by: Max Novich <mnovich@squareup.com> Co-authored-by: Best Codes <106822363+The-Best-Codes@users.noreply.github.com> Co-authored-by: caroline-a-mckenzie <cmckenzie@squareup.com> Co-authored-by: Michael Neale <michael.neale@gmail.com>
45 lines
1.3 KiB
TypeScript
45 lines
1.3 KiB
TypeScript
import React, { createContext, useContext, useState, ReactNode } from 'react';
|
|
|
|
interface DraftContextType {
|
|
getDraft: (contextKey: string) => string;
|
|
setDraft: (contextKey: string, draft: string) => void;
|
|
clearDraft: (contextKey: string) => void;
|
|
}
|
|
|
|
const DraftContext = createContext<DraftContextType | undefined>(undefined);
|
|
|
|
export const DraftProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
|
// Store all drafts by contextKey
|
|
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
|
|
|
const getDraft = (contextKey: string): string => {
|
|
return drafts[contextKey] || '';
|
|
};
|
|
|
|
const setDraft = (contextKey: string, draft: string) => {
|
|
setDrafts((prev) => ({ ...prev, [contextKey]: draft }));
|
|
};
|
|
|
|
const clearDraft = (contextKey: string) => {
|
|
setDrafts((prev) => {
|
|
const newDrafts = { ...prev };
|
|
delete newDrafts[contextKey];
|
|
return newDrafts;
|
|
});
|
|
};
|
|
|
|
return (
|
|
<DraftContext.Provider value={{ getDraft, setDraft, clearDraft }}>
|
|
{children}
|
|
</DraftContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useDraftContext = (): DraftContextType => {
|
|
const context = useContext(DraftContext);
|
|
if (context === undefined) {
|
|
throw new Error('useDraftContext must be used within a DraftProvider');
|
|
}
|
|
return context;
|
|
};
|