0

I do a request (fetch) in JSON file and y want to save a response's part in variable to export it in a VUE.js component. But the value don't change.

let Name ="0"; 

fetch("./src/assets/dataUser.json")
.then(response => response.json())
.then(response => {Name = response["prenom"]; console.log(Name)});

export default{
  data () {
        return {
        firstname: Name
        }
    }
} 

The log return the name but the value stay at "0". This is scop probleme but i don't know how to solved that.

rahan
  • 61
  • 1
  • 1
  • 5
  • `const response = await fetch(url); const data = await response.json(); Name = data.prenom;` Otherwise, you `export` something before your async call is over. – Jeremy Thille Jul 29 '21 at 14:00
  • This is not scope but timing problem. The request needs some time to complete while you most likely give it none. `firstname` cannot be initially set because the request is asynchronous. It needs to be assigned on mount. – Estus Flask Jul 29 '21 at 14:05

0 Answers0