Using type as an argument in a hook in a similar fashion to how it is

My custom hook utilizes Zustand and is capable of storing various data types. However, I am looking to specify the type of data that will be stored similar to how it is done 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 };
        }),
}));

When using this hook within a component, it should be implemented as follows:

const {actionData, setActionData} = useActionData<Profile>()

By specifying <Profile>, TypeScript will flag an error if attempting to assign any other type of data to actionData. This ensures that actionData will always be of type Profile.

Answer №1

If you want to make the useActionData hook more generic so that you can specify the type when using it in a component, you can do so by adjusting the ActionDataStore and the useActionData hook to be generic. Here's an example of how you can achieve this:

import { create } from "zustand";
import { Profile, Product, Category } from "@/types";

type ActionData = Product | Category | Profile | null;

type ActionDataStore<T extends ActionData> = {
  actionData: T;
  setActionData: (actionData: T) => void;
};

export const useActionData = <T extends ActionData>(
  defaultData: T | null = null
) =>
  create<ActionDataStore<T>>((set) => ({
    actionData: defaultData,
    setActionData: (actionData) =>
      set((state) => {
        return { actionData };
      }),
  }));

// Example of using the hook with Profile type
const { actionData, setActionData } = useActionData<Profile>();

I hope this explanation helps!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Path for WebStorm file watcher's output

I'm in the process of setting up a Typescript project in WebStorm, where I want the files to be transpiled into a dist folder. This is my current project folder structure: projectroot/src/subfolder/subfolder/index.ts What I aim for is to have the f ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

Creating a generic component map resolver for flexible applications

Currently, I am engaged in a project where the backend allows for the modeling of dynamic content that is later displayed as Components on the frontend. Everything seems to be functioning well, except when dealing with models where the dynamic content con ...

When the React router remounts the component, the state remains unchanged

I am utilizing React Router to display different components. The setup is as follows: ReactDOM.render( <Provider store={store}> <Router> <div> <Route exac ...

Typedoc Error: Attempted to assign a value to an undefined option (mode)

After installing typedoc with the command npm install typedoc --save-dev, I proceeded to add typedocOptions to tsconfig.json: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", // ...some lin ...

Error: Incorrect format detected. Expected a numerical value, but received: "t". This issue occurred when attempting to provide a slug URL to the GraphQL query function within a Next.js application

Encountering an error while attempting to retrieve content based on the URL. Here is the query function being used: const getSlugQuery = (slug) => { const SLUG_QUERY = gql` query ($slug: String!) { postCollection(where:{slug:${slug}}) { ...

React opacity transition component not switching fade direction

I'm in the process of developing a compact component that smoothly transitions between its child elements when triggered by one of its methods. I have been referencing this code for guidance, but I am aiming to make it compatible with any number of ch ...

Next.js - Reconstructing exclusively fresh sections

I'm currently working on developing a website that will only update two pages and create one new page daily. To achieve this, I need to utilize an API route in a NodeJs backend for creating the new page and updating content through an API to update th ...

I'm encountering an issue where Typescript is unable to locate the Firebase package that I

I have a TypeScript project that consists of multiple .ts files which need to be compiled into .js files for use in other projects. One of the files requires the firebase package but it's not being found. The package is installed and located inside t ...

Tips for automatically updating a MaterialUI DataGrid in a React JS application

Here's an overview of my current project: Users can save rows from deletion by clicking checkboxes (multiple rows at a time). Any unchecked records are deleted when the user hits the "purge records" button. I received some guidance on how to achieve ...

Alter the hyperlink to a different value based on a specific condition

I need help with implementing a login feature on my app. The idea is that when the user clicks the login button, it should trigger a fetch request to log in with their credentials. If the login is successful, the button's value should change to redire ...

Nextjs compatibility with React slick

For my upcoming project in Next.js, I'm considering incorporating the React-slick library for an image slider. However, I've encountered a problem during the installation process. I attempted to install "react-slick" and "slick-carousel" as outl ...

Executing a Function Prior to onClick Event of a Link Element in Next.js

While working on a slider/carousel, I encountered an issue. Each photo in the slider should be draggable back and forth, with a click taking the user to a product page. I am using next.js with react-flickity-component for this purpose. Please note that thi ...

Challenge with Typescript Interfaces

Can someone help me with understanding interfaces in typescript? I am currently facing an issue with the code. The error message says: Type 'Response' is missing the following properties from type 'myObj': userId, title, id I believe ...

Fairly intricate React function component declaration with TypeScript

const withAuth = () => <OriginalProps extends {}>( Component: React.ComponentType<OriginalProps & IAuthContextInterface> ) => { } (withAuth()(PrivateRoute)) // this is how the HOC called Could someone simplify what this function d ...

Implementing typing for a module that exports an instance of a particular class

Attempting to create a .d.ts file for the foo-foo-mq module has presented some challenges. Following the documentation, a 'foo-foo-mq' folder was created within the 'typings' directory at the project's root. An index.d.ts file was ...

Encountering a problem while trying to install the Firebase module on Node.js: getting a

I am interested in integrating Firebase into my React application. As a newcomer to React, I followed this tutorial to create my app: https://reactjs.org/tutorial/tutorial.html My environment details: Node.js version: v8.9.4 npm version: 5.6.0 Upon ...

The onTableChange function in Mui-Datatable does not seem to be functioning properly when attempting to

Utilizing mui-datatable, I came across an official example on codesandbox where setState can be used on the tableState. You can check out the example here: https://codesandbox.io/s/trusting-jackson-k6t7ot?file=/examples/on-table-init/index.js handleTableIn ...

Mern, Issue with Removing Comments

Having trouble deleting comments within a single post? I keep encountering a 404 Error and I'm not sure why the post is not being found. I really need some assistance in figuring out what's causing this issue and why I'm unable to delete a c ...