score:427
Use this
const [user, setUser] = useState<IUser>({name: 'Jon'});
score:0
class Form {
id: NullNumber = null;
name = '';
startTime: NullString = null;
endTime: NullString = null;
lunchStart: NullString = null;
lunchEnd: NullString = null;
[key: string]: string | NullNumber;
}
export const EditDialog: React.FC = () => {
const [form, setForm] = useState<Form>(new Form());
const inputChange = (e: ChangeEvent<HTMLInputElement>) => {
const element = e.target;
setForm((form: Form) => {
form[element.name] = element.value;
return form;
})
}
return (
<Box pt={3}>
<TextField
required
name="name"
label="Наименование"
defaultValue={form.name}
onChange={inputChange}
fullWidth
/>
</Box>
);
}
score:1
https://fettblog.eu/typescript-react/hooks/
// import useState next to FunctionComponent
import React, { FunctionComponent, useState } from 'react';
// our components props accept a number for the initial value
const Counter:FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
// since we pass a number here, clicks is going to be a number.
// setClicks is a function that accepts either a number or a function returning
// a number
const [clicks, setClicks] = useState(initial);
return <>
<p>Clicks: {clicks}</p>
<button onClick={() => setClicks(clicks+1)}>+</button>
<button onClick={() => setClicks(clicks-1)}>-</button>
</>
}
score:2
You could also declare the initial state before and then be able to call it any time you want:
type User = typeof initUser;
const initUser = {name: 'Jon'}
...
const [user, setUser] = useState<User>(initUser);
About I interface prefixes: https://basarat.gitbooks.io/typescript/content/docs/styleguide/styleguide.html#interface
score:31
First useState
takes a generic, which will be your IUser. If you then want to pass around the second destructured element that is returned by useState
you will need to import Dispatch. Consider this extended version of your example that has a click handler:
import React, { useState, Dispatch } from 'react';
interface IUser {
name: string;
}
export const yourComponent = (setUser: Dispatch<IUser>) => {
const [user, setUser] = useState<IUser>({name: 'Jon'});
const clickHander = (stateSetter: Dispatch<IUser>) => {
stateSetter({name : 'Jane'});
}
return (
<div>
<button onClick={() => { clickHander(setUser) }}>Change Name</button>
</div>
)
}
See this answer.
Source: stackoverflow.com
Related Query
- Set types on useState React Hook with TypeScript
- Typescript types of composition Ramda lens with React useState set function
- Set multiple state values with React useState hook
- optional react useState types with jsdoc, typescript checkjs (javascript)
- How to use useState hook in React with typescript correctly?
- Typescript error when use react useState hook with generics
- abort state set with React useState hook function call
- How to define TypeScript types when used with React useState and the previous state inside a state updating function?
- Unable to set loading indicator with useState hook in React
- how can i pass a useState hook defined with typescript down to another react component?
- How to use callback with useState hook in react
- React prop types with TypeScript - how to have a function type?
- Displaying an array received from Usestate hook with Typescript
- React hook useRef not working with styled-components and typescript
- How to prevent race conditions with react useState hook
- React efficiently update object in array with useState hook
- How to correctly set initial state in React with Typescript without constructor?
- Updating Parent Component State from Child Component with UseState React Hook
- How to use React Context with useState hook to share state from different components?
- How do you set the Typescript type for useRef hook in React Native?
- How to set multiple values at once in react hook form using Typescript
- React useTable hook with typescript
- React useState Hook setter has no result with array variable
- how can I test if useState hook has been called with jest and react testing library?
- How does React useState hook work with mutable objects
- React Apollo useQuery hook with TypeScript
- Typescript React stateless function with generic parameter/return types
- React Custom Hook with Typescript Type error "Property 'x' does not exist on type 'interface | (({ target }: any) => void)'.ts(2339)"
- How to test with jest and typescript with types a basic react function component
- React useState hook not updating with axios call
More Query from same tag
- how to sort the data from json for the different different routes?
- React CASL conditions not working in production mode - Reactjs
- Jest | Testing Utility Function that accepts multiple parameters
- how redux works here, i am going through a code base and did not understand how the function under another function dispaches
- Conditional rendering in react prop
- how to redirect websocket request through node js from reactjs to java server
- How to filtering between array of sub arrays and array of sub arrays in javascript?
- Add margin or padding to React-Bootstrap's Form.Label
- Transpiled code gives TypeError:is not a constructor
- When I change the route, the new page appears from below
- Single page application with HttpOnly cookie-based authentication and session management
- Creating Back To Top button with chakra ui
- Using setState inside useEffect on updating forms
- Using React's immutable helper with Immutable.js
- How to access dynamic route parameters when preloading server-side render
- React color ChromePicker alpha slider does not work. Is required use Alpha individual API?
- React: How to redirect
- React Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `App`
- Can't input on other Form Fields
- Chaining async functions with pure React?
- Struggling to Get Array Data From Redux Store
- .tsx webpack compile fails: Unexpected token <
- ReactJS Flux: detect store data change between components (not parent and child relationship)
- Can class object be called from React Component Prop?
- How to read props inside a socket.io callback?
- Routing to a new component from react-bootstrap-table-next?
- Created a Quiz using React, trying to create bookmarking system where users can bookmark questions from quiz
- Reactjs - writing a function to enable a button on validation of input text
- How to track value of undefined variable in dependency list in useEffect in React and Next.js
- react link vs a tag and arrow function