Leem.fin
Leem.fin

Reputation: 42622

use useState hook, however the setter function is undefined at runtime

I am using useState hook in my react-native project. I have a screen which renders my custom component named MyComponent. The setter function of state is called in MyComponent 's onSelected callback.

import React, {useState} from 'react';
import MyComponent from './components/MyComponent'

const MyScreen=()=> {
  ...
  const {parts, setParts} = useState(initialParts);

  return (<View>
           <MyComponent onSelected={()=> {
                                 ...
                                 setParts(newParts)
                                   }}/>
        </View>)
}
...

MyComponent looks like this, in the onPress callback of TouchableOpacity, it calls the passed in onSelected function:

const MyComponent= ({onSelected})=> {
  ...
  return (<TouchableOpacity onPress={()=>{
                                      onSelected();
                                      ...
                                      }}>
           ...
          </TouchableOpacity>)
 }

When I run my app on iOS emulator, the screen shows, when I tap on MyComponent, I get error TypeError: setParts is not a function. (In setParts(newParts)), 'setParts' is undefined.

Why I get this error?

Upvotes: 1

Views: 1126

Answers (2)

Handi
Handi

Reputation: 67

Hmmm, it seems like you have to read the React official documentation to know more about UseState.

here is fix to your code:

const MyScreen = () => {
  const [parts, setParts] = useState(initialParts) // see this fix.

  return (
    <View>
      <MyComponent
        onSelected={() => {
          setParts(newParts)
        }}
      />
    </View>
  )
}

basically, it is in the form of array de-structuring instead of object like you wrote above.

learn more: https://reactjs.org/docs/hooks-state.html

Upvotes: -1

Giorgi Moniava
Giorgi Moniava

Reputation: 28664

Your destructuring here seems wrong:

  const {parts, setParts} = useState(initialParts);

Shouldn't be this:

  const [parts, setParts] = useState(initialParts);

?

Upvotes: 2

Related Questions