I'm trying to create a context in a React project using TypeScript. It's my first time with TypeScript and i'm getting an error. I tried to create some interfaces to solve the problem but I'm couldn't find a way to go around this.
Here's my context file:
import React, { createContext, useState, ChangeEvent } from 'react';
interface ITransaction {
name: string;
amount: string;
}
interface ITransactions {
transactionsList: ITransaction[]
}
export const TransactionsContext = createContext({})
export const TransactionsContextProvider: React.FC = ({ children }) => {
const [transactions, setTransactions] = useState<ITransactions[]>([])
const [inputs, setInputs] = useState<ITransaction>({
name: '',
amount: ''
})
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target
setInputs({...inputs, [name]: value })
}
const handleSubmit = (e: ChangeEvent<HTMLInputElement>) => {
e.preventDefault()
setTransactions([...transactions, inputs]) <-- Error here
}
return (
<TransactionsContext.Provider value={transactions}>
{children}
</TransactionsContext.Provider>
)
}
The error that I'm getting
Argument of type '(ITransaction | ITransactions)[]' is not assignable to parameter of type 'SetStateAction<ITransactions[]>'.
Type '(ITransaction | ITransactions)[]' is not assignable to type 'ITransactions[]'.
Type 'ITransaction | ITransactions' is not assignable to type 'ITransactions'.
Property 'transactionsList' is missing in type 'ITransaction' but required in type 'ITransactions'.