How to use ts generics
Unanswered
Satin Angora posted this in #help-forum
Satin AngoraOP
"use client";
You guys see the ActionData type ? how can I pass it from where i'm calling the hook for example so that the type of action data will be the one i passed
import { useState, createContext, useContext } from "react";
type ActionData = User | Product | Category | Order | Coupon | null;
type ActionContext = {
actionData: ActionData;
setActionData: React.Dispatch<React.SetStateAction<ActionData>>;
};
const ActionContext = createContext<ActionContext>({} as ActionContext);
export const useActionData = () => useContext(ActionContext);
// This will store any type of data when a modal/drawer is open,
// and should be set to null whenever that same modal/drawer is closed
const ActionContextProvider = ({ children }: { children: React.ReactNode }) => {
const [actionData, setActionData] = useState<ActionData>(null);
return (
<ActionContext.Provider value={{ actionData, setActionData }}>
{children}
</ActionContext.Provider>
);
};
export default ActionContextProvider;You guys see the ActionData type ? how can I pass it from where i'm calling the hook for example so that the type of action data will be the one i passed
const {actionData} = useActionData<Product>()32 Replies
Oh I understand now
In the useActionData function/hook put
export const useActionData<ActionType> = () => useContext(ActionContext) as ActionType@Jesse In the useActionData function/hook put
ts
export const useActionData<ActionType> = () => useContext(ActionContext) as ActionType
Satin AngoraOP
I wanna specify which one is, the ActionType is for example x | y | z types
i wanna specify that in my component where im using it it's gonna be y for example
yeah
Satin AngoraOP
using generics
that's what the code will do
This is a generic.
export const useActionData<ActionType> = () => useContext(ActionContext) as ActionTypeSatin AngoraOP
lemme try
it shows as wrong syntax
where
Satin AngoraOP
export const useActionData<ActionType> = () => useContext(ActionContext) as ActionType
the <ActionType> trusn gray
the editor won't even allow me to save
change it to.
as {
actionData: ActionType
}You've got too things named actionContext you might want to change that as well
Satin AngoraOP
yeah vscode wouldn't prevent me from saving in that case wpuld it ?
by vscode i just mean that prettier gives an error on saving
ik
Satin AngoraOP
it's just like useState
you can tell it that it's gonna be a state for a number
const [x, setX] = useState<number>(0)
same thing with my case
Satin AngoraOP
still gives a syntax error
JSX element ActionType has no corresponding closing tag.
it thinks that it's jsx when u wrap it in #Unknown Channel
export it as a function instead of a const
does it work?
Satin AngoraOP
i will try in a few mins I have to go now sorry for wasting your time