Home > Software design >  TypeScript React createContext() default value
TypeScript React createContext() default value

Time:11-15

I been kinda stumped for a couple hours trying to figure out what to set as my default value on my createContext function. This is my code.

// PetTypeProvider.tsx
import { useState, createContext, useContext } from 'react';

const PetTypeContext = createContext('');

const UpdatePetTypeContext = createContext((event:React.MouseEvent<HTMLElement>) => event);

export function usePetType() {
  return useContext(PetTypeContext)
}

export function useUpdatePetType() {
  return useContext(UpdatePetTypeContext)
}


interface PetTypeProviderProps {
  children: JSX.Element|JSX.Element[];
}

export const PetTypeProvider: React.FC<PetTypeProviderProps> = ({children}) => {
  const [petType, setPetType] = useState('Dogs');
  const togglePet = (event:React.MouseEvent<HTMLElement>) => setPetType(event.currentTarget.innerText);
  return (
    <PetTypeContext.Provider value={petType}>
      <UpdatePetTypeContext.Provider value={togglePet}>
        {children}
      </UpdatePetTypeContext.Provider>
    </PetTypeContext.Provider>
  );
};

On my <UpdatePetTypeContext.Provider> I set the value to my toggle function, which switches the pet type to which ever is selected.

  const togglePet = (event:React.MouseEvent<HTMLElement>) => setPetType(event.currentTarget.innerText);

TS compiler is yelling at me with this

Type '(event: React.MouseEvent<HTMLElement>) => void' is not assignable to type '(event: React.MouseEvent<HTMLElement>) => React.MouseEvent<HTMLElement, MouseEvent>'.
  Type 'void' is not assignable to type 'MouseEvent<HTMLElement, MouseEvent>'.ts(2322)
index.d.ts(329, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<(event: MouseEvent<HTMLElement, MouseEvent>) => MouseEvent<HTMLElement, MouseEvent>>'

Thanks for taking the time to read my issue

I have tried setting the to const PetTypeContext = createContext(MouseEvent); which didn't work. I honestly just need the correct default value and data type for TS and I am just lost. The code works, but TS compiler doesn't like it since no default value is given.

CodePudding user response:

Try the following

const UpdatePetTypeContext = createContext((event:React.MouseEvent<HTMLElement>) => {});

You want to have a function that returns nothing, not a function that returns the event itself.

CodePudding user response:

I'm pretty sure you don't want to return event from the handler

change:

(event:React.MouseEvent<HTMLElement>) => event

to:

(event:React.MouseEvent<HTMLElement>) => {}
  • Related