dimanche 17 septembre 2017

How to make an array accessible under different functions in Javascript?

Im using React Table to fetch data from an API and populating it in the table. I make an API call and get the data. Once I have the data, I extract a field which contains the email ids and then make an array(emailList). Now I want to use the data in emailList as the part of the body in the POST API call afterwards. So in the code below, the recipients parameter under the POST call should contain the data of emailList. The emailList is declared as an empty array globally in the render method. With my current setup, I get an undefined error due to scoping issues. How to make the value accessible under the POST call? I have gone through few scoping StackOverflow answers and tried but didn't get the result.

    columns: [
    {
filterable: false,
Header: 'Action',
accessor: 'action',
Cell: (e) => (
  <button
      onClick={() => {
        axios.get(URL, {
          headers: {
            'content-type': 'application/json',
            'Name' : user.Name,
          },
          responseType: 'json',
        })
        .then((response) => {
          let responseData = response.data.data;
          function getEmailList(input, email) {
            var output = [];
            for (var i=0;i<input.length; ++i)
              output.push(input[i][email]);
            return output;
          }
          emailList = getEmailList(responseData, "email");

          function fetchEmail() {
            this.emailList = getEmailList(responseData, "email");
          }  

        });

        //console.log(new fetchEmail().emailList);
        //Unable to get the value of emailList here
        axios({
          method: 'post',
          url: URL2,
          headers: {
            'content-type': 'application/json',
            'Name' : user.Name,
          },
          data: {
            "topic": "product",
            "message": {
               "sender": "user1@xyz.com",
               //For illustration I have hardcoded the email arrays for recipients
               "recipients": ["support1@xyz.com", "support2@xyz.com"],
              "data": {
                        "text": "refresh"
              },
           "attachment": null,
           "type": "",
            },
          },
        })




Aucun commentaire:

Enregistrer un commentaire