Export data returned by 'fetch' from a separate .js file in React

佐手、 提交于 2019-12-31 03:36:09

问题


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.


回答1:


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();
}



回答2:


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";


来源:https://stackoverflow.com/questions/48380991/export-data-returned-by-fetch-from-a-separate-js-file-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!