Why is my list item calling functions it should not?

Viewed 70

Hi I've build a list component in React Native for my settings page. I want each component on the settings page to have a function (in some cases not).

I've created a array with objects where I place each items attribute.

 const list = [
            {
              title: 'Change user settings',
              icon: 'account-circle',
              link: 'UserEdit',
              action: this.noFunction()
            },
            {
              title: 'Logout',
              icon: 'exit-to-app',
              link: 'Auth',
              action: this.sessionFunction()
            },
        ]

Right now I've got two list items each with their own function applied to their action attribute.

When I press a single listItem in my app it calls both functions.

However I want only the function associated to the app be applied.

How can I do this? And what in my code is causing this bug?

      noFunction(){
        console.log('noFunction')
      }

      sessionFunction =() => { 
        console.log('sessionFunction')
        this.deleteSession().then(() => {
          this.props.destroySession();
        })
      }

    render(){ 
        const list = [
            {
              title: 'Change user settings',
              icon: 'account-circle',
              link: 'UserEdit',
              action: this.noFunction()
            },
            {
              title: 'Logout',
              icon: 'exit-to-app',
              link: 'Auth',
              action: this.sessionFunction()
            },
        ]
        return (
            <View>
                {
                    list.map((item, i) => (
                    <ListItem
                        key={i}
                        title={item.title}
                        leftIcon={
                            { name: item.icon }
                        }
                        onPress={() => {
                          item.action
                          this.props.navigation.navigate(item.link)
                          }}
                    />
                    ))
                }
            </View>
            )
        }

    }
2 Answers

Just remove () from the functions.

When you have something like action: this.noFunction() you are executing the function and assigning it to action so foo.action will be the value returned from noFunction call (wich in you case is undefined because noFunction doesn't return anything).

If you pass it like action: this.noFunction you only pass the reference to the function and later on you can do foo.action() and call noFunction.

You need to remove the invoke expression ().

Related