I'm writing a simple program in React-TypeScript that allows users to submit and render text to the browser.
Upon submit, a new object is generated, that object is saved to state as document, which is then spread into a new piece of state called choreList, as follows:
const handleSubmit = (e: React.FormEvent<HTMLFormElement>)=> {
e.preventDefault()
let doc = new ChoreDoc(name,chore,date)
setDocument(doc)
setChoreList([...choreList,document])
}
My problem is that I'm getting the following linting error, associated with [...choreList,document]:
Argument of type '(ChoreDoc | null)[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
Type '(ChoreDoc | null)[]' is not assignable to type 'never[]'.
Any suggestions of how I can type my submit function in order to fix this?
Code in full:
App.tsx
import React, {useState} from 'react';
import Document from './Document'
import './styles.css'
interface Formatter {
format(): string
}
class ChoreDoc implements Formatter {
name:string
chore:string
date:string
constructor(n:string,c:string,d:string){
this.name = n
this.chore = c
this.date = d
}
format(){
return `${this.name} completed this following chore: ${this.chore} (on date: ${this.date})`
}
}
function App() {
const [name, setName] = useState('')
const [chore, setChore] = useState('')
const [date, setDate] = useState('')
const [document, setDocument] = useState<ChoreDoc | null>(null);
const [choreList, setChoreList] = useState([])
const handleNameChange = (e:React.FormEvent<HTMLInputElement>) => {
e.preventDefault()
setName(e.currentTarget.value)
}
const handleChoreChange = (e:React.FormEvent<HTMLInputElement>) => {
e.preventDefault()
setChore(e.currentTarget.value)
}
const handleDateChange = (e:React.FormEvent<HTMLInputElement>)=> {
e.preventDefault()
setDate(e.currentTarget.value)
}
const handleSubmit = (e: React.FormEvent<HTMLFormElement>)=> {
e.preventDefault()
let doc = new ChoreDoc(name,chore,date)
setDocument(doc)
setChoreList([...choreList,document])
}
return(
<>
<div>
<form className = 'input-list' onSubmit = {handleSubmit} >
<label>
Enter Name <br></br>
<input type = 'text' name = 'name' onChange = {handleNameChange}></input>
</label>
<label>
Chore <br></br>
<input type = 'text' name = 'chore' onChange = {handleChoreChange}></input>
</label>
<label>
Date completed <br></br>
<input type = 'text' name = 'date' onChange = {handleDateChange}></input>
</label>
<div>
<button type = 'submit' >Submit</button>
</div>
</form>
</div>
<div>
{document && <Document document={document}/>}
</div>
</>
)
}
export default App;
Document.tsx
import React from 'react'
interface Formatter {
format(): string
}
interface Props {
document: Formatter;
}
const Document: React.FC<Props> = ({ document }) => {
return <h1 className="doc">{document.format()}</h1>;
};
export default Document