0

I'm trying to duplicate an input using useState with interface. Every time I click on the + button, the interface has to duplicate in the state and thus duplicate my input.

This is the code I am trying to do.

interface newInputsInterface {
    companyName?: string
    cargo?: string
    inicio?: string
    termino?: string
  }

  const [newInputs, setNewInputs] = useState<newInputsInterface[]>([new newInputsInterface])

  const onChangeInput = (
    state: any,
    setState: any,
    propName: string,
    e: any,
    i: number
  ) => {
    const arr = [...state]
    const item = arr[i]
    item[propName] = e.target.value
    setState(arr)
  }

return(
{InputsMap.map((card, i) => (
            <div key={i}>
              <div>
                <Input
                  placeholder={card.placeholder1}
                  isLegalPerson={true}
                  title={card.title1}
                  onChange={(e) =>
                    onChangeInput(newInputs, setNewInputs, card.title1, e, i)
                  }
                  value={newInputs[i]}
                />
                <Input
                  placeholder={card.placeholder2}
                  title={card.title2}
                  onChange={(e) =>
                    onChangeInput(newInputs, setNewInputs, card.title2, e, i)
                  }
                  value={newInputs[i]}

                />
              </div>
                <button
                  onClick={() => {
                    const arr = [...newInputs]
                    arr.push(new newInputsInterface)
                    setNewInputs(arr)
                  }}
                >
                  +
                </button>
              </div>
          ))}

)

if you notice I'm trying to make a new interface inside useState so I can duplicate it, but it's giving this error:

'newInputsInterface' only references one type, but is currently being used as a value.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

0

That's because you use your interface as a value here [new newInputsInterface]. The interface is used to declare types. So if you need a default value for newInputs it might look like this:

const defaultVaule = {}: newInputsInterface
const [newInputs, setNewInputs] = useState<newInputsInterface[]>([defaultVaule])
 

Not tested but you should get the idea.

See related question: Set types on useState React Hook with TypeScript.

peresleguine
  • 2,343
  • 2
  • 31
  • 34