0

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'.
0

1 Answer 1

1

Your transactions is of type ITransactions[] which means it is expecting value in this form:

[
{transactionsList:{name:'',amount:''}},
{transactionsList:{name:'',amount:''}},
{transactionsList:{name:'',amount:''}}
]

Now here setTransactions([...transactions, inputs]) <-- Error here when you are updating state you trying to put only the object {name:'',amount:''} in the array but not {transactionsList:{name:'',amount:''} , and hence the error.

Try this:

setTransactions([...transactions,{transactionsList:inputs}])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.