Home > front end >  React Context error: Type 'Dispatch<SetStateAction<GiftsType>>' is not assigna
React Context error: Type 'Dispatch<SetStateAction<GiftsType>>' is not assigna

Time:01-01

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>;
}

CodePudding user response:

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.

CodePudding user response:

Your problem is here :

export function GiftsProvider({ children }) {
  const [choices, setChoices] = useState<GiftsType>({
    choices: [],
    links: [],
    setChoices: (arr1: string[], arr2: string[]) => void {}, // change the name
  });

  return <GiftsContext.Provider value={{ ...choices, setChoices }}> {children}</GiftsContext.Provider>;
}

You're using the same name as your state setter function and in the value that you are using spread operator you'll have two setChoices which is wrong.

CodePudding user response:

Your GiftType needs the setGift function.

The value you're giving the provider is essentially

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

But it's expecting

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

Simply amend your GiftType (Type in the name is redundant, you could just name the type Gift) to include this function

  • Related