I'm creating a context using Typescript for the first time, and I'm having a hard time making it work. Everytime I try to create interfaces and put them in my value prop I get errors, and I really need some help. Here's my context(I'll point the errors in comments)
In the IContext, I don't know how can I put the type of the transactions(it is an array of objects)
I'd like to pass everything in the value prop, the two functions, the transactions array, and the inputs.
anyway, that's my first time applying typescript in a bigger project, so if you guys have any advices on how to practice it better, just let me know.
import React, { createContext, useState, ChangeEvent } from 'react';
interface IContext {
handleInputChange(): void;
handleSubmit(): void;
inputElements: {
name: string;
amount: string;
};
transactions: <-- I don't know what to put here
}
export const TransactionsContext = createContext<IContext | null>(null)
interface ITransaction {
name: string;
amount: string;
}
interface ITransactions {
transactionList: ITransaction
}
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, handleInputChange, handleSubmit, inputs }}> <-- Error here
{children}
</TransactionsContext.Provider>
)
}
Error
In the setTransactions:
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 'transactionList' is missing in type 'ITransaction' but required in type 'ITransactions'.