I have a custom hook built with Zustand that can store multiple types of data, but I want to be able to pass the type I will be using just like with the useState hook
import { Profile } from "@/types";
import { create } from "zustand";
type ActionData = Product | Category | Profile | null;
type ActionDataStore = {
actionData: ActionData;
setActionData: (actionData: ActionData) => void;
};
export const useActionData = create<ActionDataStore>((set) => ({
actionData: null,
setActionData: (actionData) =>
set((state) => {
return { actionData };
}),
}));
This is how it should look like when I use it inside a component:
const {actionData, setActionData} = useActionData<Profile>()
Typescript should give me an error whenever i try to set the action data to anything other than a profile now. And actionData should be of type Profile aswell
To make the useActionData hook generic so that you can specify the type when using it in a component. You can achieve this by making the ActionDataStore and the useActionData hook generic. Try the code below:
enter code hereHope that helps