M
M
mayorpvk2020-04-26 09:55:08
JavaScript
mayorpvk, 2020-04-26 09:55:08

How to call FETCH once?

Hello.
There is a request in which the data comes.
How and where is it better to write them down so that they can be used in other functions?

function func() {
    fetch('bla-bla-bla')
        .then(data => data.json())
        .then(data => data)
}


I want to use data in other functions.
Sorry for stupid question :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Elvis, 2020-04-26
@mayorpvk

Declare a variable outside the function and put the result of the fetch in it.

M
Mikhail Ushenin, 2020-04-26
@usheninmike

const func = (() => {
    const url = 'bla-bla-bla';
    let result;

    return async () => {
        if (typeof result == 'undefined') {
            result = await (() => {
                return fetch(url).then(response => response.json());
            })();
        }

        return result;
    };
})();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question