Untitled

 avatar
unknown
plain_text
4 months ago
2.1 kB
4
Indexable
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

interface RFQWizardContextType {
  rfqDescription: string;
  setRfqDescription: (description: string) => void;
  tableOfContents: string[];
  setTableOfContents: (toc: string[]) => void;
  sectionDescriptions: Record<string, string>;
  setSectionDescriptions: (descriptions: Record<string, string>) => void;
}

const RFQWizardContext = createContext<RFQWizardContextType | undefined>(undefined);

const LOCAL_STORAGE_KEY = 'RFQWizardData';

export const WizardProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  // Load from local storage or initialize to defaults
  const [state, setState] = useState(() => {
    const storedData = localStorage.getItem(LOCAL_STORAGE_KEY);
    if (storedData) {
      return JSON.parse(storedData);
    }
    return {
      rfqDescription: '',
      tableOfContents: [],
      sectionDescriptions: {},
    };
  });

  // Destructure state for ease of use
  const { rfqDescription, tableOfContents, sectionDescriptions } = state;

  // Update the state and persist to local storage
  const updateState = (updatedValues: Partial<typeof state>) => {
    const newState = { ...state, ...updatedValues };
    setState(newState);
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(newState));
  };

  return (
    <RFQWizardContext.Provider
      value={{
        rfqDescription,
        setRfqDescription: (description) => updateState({ rfqDescription: description }),
        tableOfContents,
        setTableOfContents: (toc) => updateState({ tableOfContents: toc }),
        sectionDescriptions,
        setSectionDescriptions: (descriptions) => updateState({ sectionDescriptions: descriptions }),
      }}>
      {children}
    </RFQWizardContext.Provider>
  );
};

export const useWizard = () => {
  const context = useContext(RFQWizardContext);
  if (context === undefined) {
    throw new Error('useWizard must be used within a WizardProvider');
  }
  return context;
};
Editor is loading...
Leave a Comment