Issue
I'm trying to use useContext() hook in typescript, but I expireance numerouse errores.
useState initialy is equal to empty array of interface Phone which is imported, and then state and setState are passed in value prop .
import { createContext, useState } from 'react';
import { Phone } from '../types/Phone';
type SetValue = (value: Phone[]) => void;
interface LikedContextInterface {
  likedGadgets: Phone[];
  setLikedGadgets: SetValue;
}
export const likedContext = createContext<LikedContextInterface>([]);
type Props = {
  children: React.ReactNode;
};
export const LikedContextProvider: React.FC<Props> = ({ children }) => {
  const [likedGadgets, setLikedGadgets] = useState<Phone[]>([]);
  return (
    <likedContext.Provider value={{ likedGadgets, setLikedGadgets }}>
      { children }
    </likedContext.Provider>
  );
};
in terminal I recieve following errors:
Argument of type 'never[]' is not assignable to parameter of type 'LikedContextInterface'.
Type 'never[]' is missing the following properties from type 'LikedContextInterface': likedGadgets, setLikedGadgets
Edited!!!
So here is working code:
import { createContext, useState } from 'react';
import { Phone } from '../types/Phone';
type SetValue = (value: Phone[]) => void;
type LikedContextInterface = {
  likedGadgets: Phone[];
  setLikedGadgets: SetValue;
};
export const likedContext = createContext<LikedContextInterface>({
  likedGadgets: [],
  setLikedGadgets: () => {},
});
type Props = {
  children: React.ReactNode;
};
export const LikedContextProvider: React.FC<Props> = ({ children }) => {
  const [likedGadgets, setLikedGadgets] = useState<Phone[]>([]);
  return (
    <likedContext.Provider value={{ likedGadgets, setLikedGadgets }}>
      { children }
    </likedContext.Provider>
  );
};
                            Solution
You have to initialize context correctly by providing initial value which is LikedContextInterface:
export const likedContext = createContext<LikedContextInterface>({
   likedGadgets: [],
   setLikedGadgets: (value: Phone[]) => {},
});
                            Answered By - Art Bauer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.