1

I'm trying to fetch some data, filter it, build an object array and then stringify it. i put in some console.logs to figure out whats happening to no avail!

log 1: [7] // array with 7 objects in it

log 2: "[]" // this is the stringified version just two brackets

log 3: [0] // after parsing it it resturns an empty array.

I need the array in stingform to save it to AsyncStorage.

This is for an react-native app, that is to be a "supportive" app to an existing .NET solution.

This is my fetch:

fetchCallHistory = async () => {
    let calls = [];
    try {
        const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.READ_CALL_LOG,
            {
              title: "Call Log Example",
              message: "Access your call logs",
              buttonNeutral: "Ask Me Later",
              buttonNegative: "Cancel",
              buttonPositive: "OK"
            }
        );

      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          CallLogs.load(200).then(function(history) {
              let todayMinus10 = new Date().getTime() - 864000000;
              let filterDate = history.filter(history => {
                  return parseInt(history.timestamp) >= `todayMinus10;`;
              });
              let filterByType = filterDate.filter(history => {
                  return history.rawType < 3;
              });
              for (let i = 0; i < filterByType.length; i++) {
                  calls.push(filterByType[i]);
              }
            });
      } else {
          console.log("Call Log permission denied");
      }
    } catch (error) {
        console.log(error);
    }

    console.log("log 1: ");
    console.log(calls);

    return (stringifiedCalls = JSON.stringify(calls));
};

this is where i call it:

async componentDidMount() {        
    const callHistory = await this.fetchCallHistory();
    console.log("log 2: ");
    console.log(callHistory);

    let parsedHistory = JSON.parse(callHistory)
    console.log("log 3: ");
    console.log(parsedHistory);

    if (callHistory !== null) {
       this.setState({ callLogs: callHistory, isLoading: false });
    }
}

expected result: log 1: [7] // array with 7 objects in it

log 2: // array converted to string with all its content

[{"rawType":1,"type":"INCOMING","dateTime":"17. jun. 2019 09:11:19","timestamp":"1560755479695","name":null,"duration":2698,"phoneNumber":"########"}, ..... ]

log 3: [7] // the same array as i started with

actual result: log 1: [7] // array with 7 objects in it

log 2: "[]" // this is the stringified version just two brackets

log 3: [0] // after parsing it it returns an empty array. EDIT: this is not to be parsed here at this point, its set up now for testing

1 Answer 1

1

You are using async await in a wront manner at permission granted code block Below code should fix it.

const history = await CallLogs.load(200);
let todayMinus10 = new Date().getTime() - 864000000;
let filterDate = history.filter(history => {
  return parseInt(history.timestamp) >= `todayMinus10;`;
});
...

Your function 'fetchCallHistory' is an async function, which needs to create a calls array and return it after 2 async operations (get permission, load call history). You were creating calls array before these 2 async operations as it should. But without waiting for CallLogs.load operation to finalise and populate calls array, you were returning the empty array.

So, your execution order was something like below:

  • create calls
  • request permission
  • wait for request permission result (by await operation)
  • request permission retured
  • create get logs promise but don't wait (mistake here)
  • log, log
  • return calls
  • execute CallLogs.load callback method (because this was in stack, waiting for a result. You were not awaiting this operation, hence the error)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for a quick reply, this solved my issue! Im not sure what the diffrence was(except the obvious change in code)
I just edited the answer with more explanation, hope it helps :) @SondreLjovshin

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.