This is my code
const data = () => fetch("https://api.myjson.com/bins/mp441")
.then(response => response.json())
.then(obj => data = obj);
const RECORD_NOS=Object.keys(data).length-1;
export {data, RECORD_NOS}
I am trying to get the json data hosted at the above url, save the data in a variable and export it for use in various places in my React application but unfortunately it gives the following error.
./src/resources/index.js
Syntax error: D:/Users/kumahay/Documents/lending-referrals-app/src/resources/index.js: "data" is read-only
1 | const data = () => fetch("https://api.myjson.com/bins/mp441")
2 | .then(response => response.json())
> 3 | .then(obj => data = obj);
| ^
4 |
5 | const RECORD_NOS=Object.keys(data).length-1;
6 |
I have tried console logging instead of assigning the data but it doesn't work. Apparently the data is not being fetched. How to better frame this code so that it works as expected? I am a beginner in javaScript so any help will be appreciated.
Example:
var data = "something";
I think you should read more about async functions, Promises and fetch. The best way is export
getData
function, remove.then(obj => data = obj)
and use it in any other module like thisgetData.js
anyOtherFile.js
or with async/await notation
getData.js
anyOtherFile.js