Export data returned by 'fetch' from a sep

2020-04-16 03:05发布

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.

2条回答
乱世女痞
2楼-- · 2020-04-16 03:51

Please change the name of data to response data and instead of constant use variable. Constant cannot be overwritten but variable can.

Example:

var data = "something";

const name ="Japarsathik";

var salary = "$5000";
查看更多
我想做一个坏孩纸
3楼-- · 2020-04-16 03:57

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();
}
查看更多
登录 后发表回答