I created a method to fetch a copy of my backend locale strings that are stored under my server document root as a JSON file.
I have a Form class that handles submitting a form and deals with showing error messages and so on.
When I use fetch to get my JSON and store in the the object as a property named locale
, this
referencing the class shows my class with a locale property being set correctly with all my translation keys and values but the next line, this.local
is undefined.
There are 2 errors in the console:
Uncaught (in promise) TypeError: this.locales is undefined Uncaught (in promise) SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
The class:
class Form
{
constructor(form)
{
this.form = form
}
getLocales()
{
if (!this.locales)
{
fetch("/locales.json")
.then(response => { response.json().then(locales => { this.locales = locales })})
}
console.log(this) // here the class is shown and the locale appears as an object
console.log(this.locales) // here this.locale is undefined
return this.locales
}
}
I was expecting to set the locales on the object and then return it.
I am absolutely certain the JSON format is correct. The browser displays it correctly.