Back

Typescript context default state

  • 0
  • General
  • Functions
  • Web
  • Cloud
larkx
20 Mar, 2024, 18:46

Hello all, I need help. I'm not sure if this was just a TypeScript issue, but it relates to Appwrite so I figured I'd ask here.

I've created a function in my code to execute an Appwrite function, and I want to return the execution, but I'm running into loads of Typescript/ESLint errors. Would anybody be able to help me and tell me what I need to put in the defaultState value for the function? Here's a simplified version of my code with only relevant parts:

TypeScript
"use client"

import { functions } from '@/lib/appwrite';
import { AppwriteException, Models } from 'appwrite';
import {
  useContext,
  createContext,
  ReactNode,
} from 'react';

  export interface FlashcardState {
    notes_to_cards: (notes: string) => Promise<Models.Execution>;
  }
  
  const defaultState: FlashcardState = {
    notes_to_cards: ????
  }
  
  const flashcardContext = createContext<FlashcardState>(defaultState);

  type FlashcardProviderProps = {
    children: ReactNode;
  };
  export const FlashcardProvider = ({ children }: FlashcardProviderProps) => {

    const notes_to_cards = async (notes: string) => {
      let payload = {
        notes: notes
      }

      try {
          const execution = await functions.createExecution('<FUNCTION ID>', JSON.stringify(payload), false, "/", "POST")
          if(execution.status == 'failed') throw new Error('Failed to execute function')
          return execution
      } catch(error) {
          if (error instanceof AppwriteException) {
            console.error(error.message);
          } else {
            console.error(error);
          }
          throw error
      }
    }

    return (
      <flashcardContext.Provider
        value={{ notes_to_cards }}
      >
        {children}
      </flashcardContext.Provider>
    );
  };
  
  export const useFlashcards = () => {
    const context = useContext<FlashcardState>(flashcardContext);
    return context;
  };
TL;DR
Problem: Developer is struggling with setting the default state value for a function in a Typescript context. Solution: Set the defaultState value for the function as an object with the function notes_to_cards defined as an async function.
Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more