Electric_Passenger
Electric_Passenger

Reputation: 35

How do you pass variables to other JS modules with Fetch API?

A JavaScript app uses Web Audio API to create sounds from JSON data. I am fetching weather data, going through the JSON data and setting their properties to variables then using those variables to manipulate my application and create sounds. Each function in it's own JavaScript module script file. The main.js not shown here is the entry point to app.

A sample JSON that will get replaced with real weather data.

dummy-data.json

{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}

The fetch API logic.

fetchWeather.js

import { manageData} from './manageScript.js';

const DUMMY = '../dummy-data.json';

const fetchWeather = () => {
    fetch(DUMMY)
        .then((res) => {
            return res.json();
        })
        .then((data) => {
            manageData(data); // attaches JSON weather properties to variables
        })
        .catch((error) => {
            console.log(error);
        });
};

export { fetchWeather };

Attaches the JSON data to variables.

manageScript.js

function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    }
    else {
        rainProbability = 0;
    }

    return rainProbability; // not sure how to return the data....?
};

export { manageData };

I want the variables from manageData function above to work here

makeSynth.js

import { manageData } from './manageScript.js';

const createSynth = () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //How do I get the variables to work here. Code below does not work!
    let soundOfRain = manageData().rainProbability;
    console.log(soundOfRain);
};

Upvotes: 0

Views: 1596

Answers (3)

Ben Aston
Ben Aston

Reputation: 55769

// dummy-data.json

{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}

// fetchWeather.js

import { getRainProbability } from './get-rain-probability.js'
import { createSynth } from './create-synth.js'

const DUMMY = '../dummy-data.json'

const fetchWeather = () => {
    return fetch(DUMMY)
        .then((res) => res.json())
        .then((data) => {
            createSynth({ rainProbability: getRainProbability(data) })
        })
        .catch((error) => {
            console.log(error)
        });
};

export { fetchWeather }

// get-rain-probability.js

function getRainProbability(data) {
    let rain = data.weather.rain

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    }
    else {
        rainProbability = 0;
    }

    return rainProbability; // not sure how to return the data....?
};


// create-synth.js

const createSynth = ({ rainProbability }) => {
    const soundOfRain = //WebAPI stuff for audio using `rainProbability`
    console.log(soundOfRain);
};

export { createSynth }

Upvotes: 0

Taki
Taki

Reputation: 17654

You can add data as a property of manageData that would return this, and access it with manageData().data; :

fetchWeather.js

const fetchWeather = () => {
  fetch(DUMMY)
    .then(res => {
      return res.json();
    })
    .then(data => {
      manageData.data = data; // attaches JSON weather properties to variables
    })
    .catch(error => {
      console.log(error);
    });
};

manageScript.js

function manageData() {
  // ...
  return this;
}

makeSynth.js

let soundOfRain = manageData().data.rainProbability;

Upvotes: 0

SenAnan
SenAnan

Reputation: 276

You can achieve this by refactoring your promises into a async/await pattern then returning the result (a different method of dealing with promises). Also - your createSynth function should be calling fetchWeather, not manageScript

dummy-data.json

{
    "weather": {
        "temp": 4,
        "rain": 1,
        "wind": 1.2
    }
}

manageScript.js

function manageData(data) {
    let rain = data.weather.rain;
    //let wind = data.weather.wind;

    let rainProbability;

    if (rain == 1) {
        rainProbability = 1;
    } else {
        rainProbability = 0;
    }

    return rainProbability;
}

export { manageData };

fetchWeather.js

import { manageData } from "./manageScript.js";

const DUMMY = "../dummy-data.json";

// Use async/await to be able to return a variable out from the promise
const fetchWeather = async () => {
    const raw = await fetch(DUMMY);
    const json_data = await raw.json();
    const rain = manageData(json_data);
    // Now you should be able to return the variable back out of the function
    return rain;
};

export { fetchWeather };

makeSynth.js

import { fetchWeather } from "./fetchWeather.js";

const createSynth = async () => {
    //Web Audio API stuff goes here to create sounds from the variables.

    //Need to call fetchWeather (which in turn will call manageData)
    let soundOfRain = await fetchWeather();
    console.log(soundOfRain);
};

createSynth();

Upvotes: 1

Related Questions