5

This is how I declare a state

const [input, setInput] = React.useState('')
const [goals, setGoals] = React.useState<string[]>([])

and this is my error code:

const addHandler = () => {
    setGoals((curGoals) => [...curGoals, { key: Math.random().toString(), value:input}])
}

This is a typescript hint:

Argument of type '(curGoals: string[]) => (string | { key: string; value: string; })[]' is not assignable to parameter of type 'SetStateAction<string[]>'. Type '(curGoals: string[]) => (string | { key: string; value: string; })[]' is not assignable to type '(prevState: string[]) => string[]'. Type '(string | { key: string; value: string; })[]' is not assignable to type 'string[]'. Type 'string | { key: string; value: string; }' is not assignable to type 'string'. Type '{ key: string; value: string; }' is not assignable to type 'string'.ts(2345)

I still don't understand why my code still outputs this error. I did use a string type of array with useState.

How can I resolve this error?

1 Answer 1

16

You declare the state as being string[] this means it is an array of strings. So an item of this state must be a string. { key: Math.random().toString(), value: input } is an object with properties value and key property of type string.

You can change the state to be of type Array<{key: string, value: string}>

const [input, setInput] = React.useState('')
const [goals, setGoals] = React.useState<
    Array<{
        key: string,
        value: string
    }>
>([])

const addHandler = () => {
    setGoals((curGoals) => [...curGoals, { key: Math.random().toString(), value: input }])
}

Playground Link

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.