Good day. There is a Fetch request, the response of which is passed to the function argument:

fetch('url') .then((resp) => resp.json()) .then( response => { getDataFromAPI(response) }, error => alert(`Rejected: ${error}`) ); export function getDataFromAPI(data) { console.log(data) } 

How do I need to import it to get data in several other files?

Reported as a duplicate at Grundy. javascript Jan 31 '18 at 5:21 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    Why not just write data into a constant and pull this constant out of other files (like a global state)?

     export const myData = []; fetch('url') .then((resp) => resp.json()) .then( response => { getDataFromAPI(response) }, error => alert(`Rejected: ${error}`) ); export function getDataFromAPI(data) { myData = data; // через константу return data; // или можно через функцию вернуть данные туда куда вам необходимо. } 

    To get this data, you must write in your other files.

     import {myData, getDataFromAPI} from 'filePath'; 

    You can also call fetch itself and return data to the component. Here is an example:

     export function getDataFromAPI() { fetch('url') .then((resp) => resp.json()) .then( response => { return response; }, error => alert(`Rejected: ${error}`) ); } 
    • The function body itself outputs. but exactly data - no - Igor Myasnikov
    • You can write data somewhere, as I suggested through a constant. Or, after calling fetch, you can return the response to the component (file) from which you call this fetch (but again you need to use this data in more than one file). You are trying to call a function that accepts input data and returns this data. But after calling the function and you will not betray anything to it, the function will return itself, Cap. Your ideal way is a global state :). - Puvvl