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.
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 this
getData.js
export const getData = () => fetch("https://api.myjson.com/bins/mp441")
.then(response => response.json())
anyOtherFile.js
import {getData} from './path/to/getData.js';
export const someFunc = () => {
getData().then(data => {
/* do what you want to do in promise resolve callback function */
})
}
or with async/await notation
getData.js
export const getData = async () => fetch("https://api.myjson.com/bins/mp441")
.then(response => response.json())
anyOtherFile.js
import {getData} from './path/to/getData.js';
export const someFunc = async () => {
const data = await getData();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With