Open
Description
Thanks for the tutorial, I'm going through the vidoes and trying to learn Hooks with typescript.
How do I get rid of the below error? Would be great to know.
https://stackoverflow.com/questions/63855787/react-hook-tsx-and-untyped-array
HookCounter.tsx
import React from 'react'
import {useState} from 'react'
interface Props{}
interface Item{
id: number;
value: number;
}
interface Person{
firstName: string;
lastName: string;
}
const HookCounter : React.FC<Props> = () => {//S1 create functional component
//S3 : method capable of setting that state var
const initialCount = 0
const [count, setCount] = useState(0) // this hook accepts initial val, and returns current val, and
const [name, setName] = useState({firstName : '', lastName: ''}) // Ch 4: object in useState
const [items, setItems] = useState([]) // Ch 5: array in useState
const incrementFive = () =>{
setCount( prevCount => prevCount+5)
}
const addItem = () => {
setItems([ ...items, //copy prev array for merge
{
id: items.length
, value: Math.floor(Math.random()*10)+1
}//newitem
]) //setItems
}//addItem
return (
<div>
Ch 3: Using previous state: <em> setCount(prevCount => prevCount +1)</em>
Count : {count}<br/>
<button onClick={() => setCount(prevCount => prevCount +1)} > More + </button><br/>
{/* For incrementfive no ()=> */}
<button onClick={incrementFive} > More +5 </button><br/>
<button onClick={() => setCount(prevCount => prevCount -1)} > Less - </button><br/>
<button onClick={() => setCount(initialCount)} > Reset </button>
<hr/>
Ch 4: Using useState with object: <em>useState(json-object)</em><br/>
Manual merge with spread operator: <em>onChange= e = setName( ...name, firstName : e.target.value )</em>
<form>
{/* TODO check why should I mention both firstname and lastname in setname() */}
<input type="text" value={name.firstName} onChange={e => setName({ ...name, firstName : e.target.value })} /><br/>
<input type="text" value={name.lastName} onChange={e => setName({ ...name, lastName : e.target.value })} /><br/>
</form>
Your first name is: <em>{name.firstName}</em><br/>
Your last name is: <em>{name.lastName}</em><br/>
state variable name : {JSON.stringify(name)}
<hr/>
Ch 5: Using useState with arrays: <em>useState(json-object)</em><br/>
<button onClick={addItem}>Add a number</button>
<ul>
{items.map(item => (
<li key={item.id}> {item.value} </li>
))}//items
</ul>
</div>
);//return
};
export default HookCounter;
Metadata
Metadata
Assignees
Labels
No labels