Home > Back-end >  How to pass 2nd argument of useState in a prop
How to pass 2nd argument of useState in a prop

Time:08-18

I'm trying to store the input state to a array state. but when i'm passing the useState function argument to a child component it says

Cannot invoke an object which is possibly 'undefined'

Parent:

const App:React.FC = () => {
  const [collection, setCollection] = useState([])
  return (
  <div>
   <Input setcollection={setCollection} />
  </div>
 )
}

Input Component(Child Component)

interface InputProps {
  setcollection?: any[]
}
const Input: React.FC<InputProps> = ({setcollection}) => {
  const [input,setInput] = useState('')
  const handleChange = (e:any) => {
    const {value} = e.target;
    setInput(value)
  }
return (
   <div className="container">
     <form>
        <input onChange={handleChange} placeholder="Input Data"/>
        <button onClick={() => setcollection(input)}>Submit</button>
    </form>
  </div>
)
}

CodePudding user response:

The reason for the TypeScript error you're getting is the fact, that you've made setcollection prop optional in InputProps. If setcollection can be undefined, TypeScript will treat any attempt to invoke it an error.

A button without an onClick event makes no sense, so it would make sense to make setcollection a required prop:

interface InputProps {
  setcollection: (input: string) => void
}

Note that I updated the type of setcollection to allow passing functions.

I'm just not sure what you're trying to achieve with it - the default value for collection is an array, but in the input component you're passing string into setcollection.

UPDATE If you want to add input value to the collection, I'd do the following changes:

// App
const addToCollection = (value:string) => setCollection([...collection, value]);

return (
  <div>
   <Input addToCollection={addToCollection} />
  </div>
)

// Input
interface InputProps {
  addToCollection: (input: string) => void
}
...
<button onClick={() => addToCollection(input)}>Submit</button>

CodePudding user response:

const App:React.FC = () => {
  const [collection, setCollection] = useState([])

 const updateCollection = collection=> setCollection(collection)

  return (
  <div>
   <Input setcollection={updateCollection} />
  </div>
 )
}

   

interface InputProps {
  setcollection?: (data:any)=>void
}

const Input: React.FC<InputProps> = ({setcollection}) => {
  const [input,setInput] = useState('')
  const handleChange = (e:any) => {
    const {value} = e.target;
    setInput(value)
  }

return (
   <div className="container">
     <form>
        <input onChange={handleChange} placeholder="Input Data"/>
        <button onClick={() => setcollection(input)}>Submit</button>
    </form>
  </div>
)
}
  • Related