0

I'm using an array to populate a settings page and some of the buttons have functions attached.

Here's what I want to do. In one file export an array with objects that refer to functions within the same file OR export a class, then access the array from within that class, referring to functions inside the class.

// import file

import Settings from './Settings';
console.log(Settings.settingsArray);

// export file

export const settingsArray = [
  {
    title: " ",
    data: [
      {
        title: "Export data",
        func: this.exportData
      }
    ]
  },
  {
    title: " ",
    data: [
      { 
        title: "Set custom code",
        func: this.showDialog
      },
    ]
  }
]

exportData = () => {
    // some code
};

showDialog = () => {
    // some code
};
3
  • 1
    What is your question exactly? What problem are you running into? Commented Jan 29, 2019 at 20:07
  • this doesn't refer to anything useful in this scope. exportData should already exist in order to be referred in an array. It should be referred without this. Commented Jan 29, 2019 at 20:08
  • Well, I used to have the entire settings tree with every function in a context which is provided to the entire app. It worked fine, except for the bad practice, until I tried saving to react native AsyncStorage using JSON.stringify, because it doesn't like functions. So I'm trying to put it in a separate file, now I just have to figure out how to connect to the context from that file. Commented Jan 29, 2019 at 20:31

1 Answer 1

3

Drop the this keyword and create the functions before using them:

const exportData = () => {
    // some code
};

const showDialog = () => {
    // some code
};

export const settingsArray = [
  {
    title: " ",
    data: [
      {
        title: "Export data",
        func: exportData
      }
    ]
  },
  {
    title: " ",
    data: [
      { 
        title: "Set custom code",
        func: showDialog
      },
    ]
  }
];

Alternatively declare them as functions and take advantage of hoisting.

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.