Handling loading, error states

Hey everyone, i was wondering if someone has any suggestions on the best way to solve a problem i am facing .

I have a WorkflowProvider component in my app that is supposed to fetch a Workflow , hold the currentStep state and provide workflowId, workflowSteps, currentStep, setCurrentStep to the components in the tree through Context. When the getWorkflow query returns a response, i initialize the currentStep to the first step in workflow.configuration.steps.

The issue: After loading becomes false, and before the component is rendered with currentStep = worflowSteps[0], the component renders with currentStep as undefined and the components that consume the Context throw an error. One solution would be to type the currentStep in the Provider as currentStep: WorkflowStep | undefined, and check if currentStep is set everytime i consume the context. Ideally i would want to do this check before passing the currentStep to the Provider, because i dont want to do this check everytime i use currentStep from the WorkflowContext.

What do you think would the best solution? Would love to hear your thoughts on this.

  const {
    data,
    loading,
    error,
  } = useGetWorkflowQuery({
    skip: !workflowId,
    variables: { workflowId },
  });

 const workflow = data?.workflow
 const workflowSteps = data?.workflow?.configuration?.steps

 const [currentStep, setCurrentStep] = useState<WorkflowStep>()

  useEffect(() => {
    if (!currentStep && workflowSteps?.length && workflowSteps[0]) {
      setCurrentStep(workflowSteps[0]);
    }
  }, [workflowSteps, currentStep]);

  if (loading) {
    return <Spinner />
  }

  if (error || !workflowId || !workflowSteps) {
    return <Error />
  }

  return (
    <WorkflowContext.Provider
      value={{
        workflowId,
        workflowSteps,
        currentStep,
        setCurrentStep
      }}
    >
      {children}
    </TreatmentContext.Provider>
  );
Was this page helpful?