0

I'm using https://www.npmjs.com/package/react-native-link-preview this library to fetch meta data from url's. I have tried it and it's working for me. I'm trying to assign the value in the promise to a variable but i cannot get it to work. How can it to a variable.

My code

 if(this.videoUrl != null){

        LinkPreview.getPreview(this.videoUrl)
            .then(data =>
                console.log("previewData ",data)
            );

    }

Here i want to use the values in data . I've tried declaring a variable and assign the value to it. But it was getting a null value. So how can i do it.

My approach

 var previewData = '';

        if(this.videoUrl != null){

            LinkPreview.getPreview(this.videoUrl)
                .then(data =>

                    previewData = data,
                    console.log("previewData ",previewData)

                );

        }
CraZyDroiD
  • 6,622
  • 30
  • 95
  • 182
  • Are you sure `this.videoUrl` is passing the proper argument to `getPreview`? – CertainPerformance Apr 23 '18 at 05:16
  • 1
    Read about [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). – axiac Apr 23 '18 at 05:18
  • 1
    Some people on [so] mark the questions as duplicate without trying to understand them. This one is not a duplicate of anything. The problem here is that `.then()` receives two arguments: the function `data => previewData = data` and the expression `console.log("previewData", previewData)`. `console.log()` is evaluated *before* `.then()` is called and prints an empty `previewData` because the arrow function that sets it didn't execute yet. – axiac Apr 23 '18 at 05:33
  • In the first code snippet, console log prints the correct data. It's just when i try to use a variable to equal it, issue comes – CraZyDroiD Apr 23 '18 at 05:36
  • 1
    The solution is simple: to achieve what you intended (put both the assignment of `previewData` and `console.log()` into the body of the callback function) you have to use a block (`{...}`): `.then(data => { previewData = data; console.log("previewData ", previewData); });`. [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) work in the simple form `arg => body` when there is only one argument and `body` is an expression. Multiple arguments must be wrapped in parentheses, multiple statements in curly braces (a block of code). – axiac Apr 23 '18 at 05:37

0 Answers0