Search code examples
reactjstypescripttypescript-typingsreact-context

React Context error: Type 'Dispatch<SetStateAction<GiftsType>>' is not assignable to type '(arr1: string[], arr2: string[]) => void'


I'm trying to create a context in React+TS, which takes 2 string arrays and updates an object's state with these arrays. But I'm getting the title typo error in setChoices inside return statement and I'm not able to solve it. Could you guys help me, please?

Code:

import { createContext, useState } from 'react';

type GiftsType = {
  choices: string[];
  links: string[];
  setChoices: (arr1: string[], arr2: string[]) => void;
};

export const GiftsContext = createContext<GiftsType>({
  choices: [],
  links: [],
  setChoices: (arr1, arr2): void => {},
});

export function GiftsProvider({ children }) {
  const [gifts, setGifts] = useState<GiftsType>({
    choices: [],
    links: [],
    setChoices: (arr1, arr2) => void {},
  });

  return <GiftsContext.Provider value={{ ...gifts, setGifts }}>{children}</GiftsContext.Provider>;
}

Solution

  • Change your code to this:

    type GiftsType = {
      choices: string[];
      links: string[];
      setChoices: (arr1: string[], arr2: string[]) => void;
      setGifts: React.Dispatch<React.SetStateAction<GiftsType>>
    };
    

    it will work.