Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript Accessing Data From Imported Script

So I’m trying to export/import script from model.js and I use this

import * as model from './model.js';

Here’s the script of model.js

export const state = {
  recipe: {},
};
console.log(state.recipe);
export const loadRecipe = async function (id) {
  try {
    const res = await fetch(
      `https://forkify-api.herokuapp.com/api/v2/recipes/${id}`
    );
    const data = await res.json();
    if (!res.ok) throw new Error(`${data.message} (${res.status})`);
    console.log(data);
    let { recipe } = data.data;
    console.log(recipe);
  } catch (err) {
    console.error(err);
  }
};

This is the render part where I’m trying to access recipe part from model.js.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const showRecipe = async function () {
  try {
    const id = window.location.hash.slice(1);
    if (!id) return;
    renderSpinner(recipeContainer);
    //1.Loading Recipe
    await model.loadRecipe(id);
    const { recipe } = model.loadRecipe.recipe;

I’m trying to access recipe part here:
const { recipe } = model.loadRecipe;

But I’m getting undefined. Please help me identify the problem, is it exporting, importing or I’m accessing data in the wrong way? Also, how should I push the recipe part to the state recipe?

Thank you very much.

>Solution :

You can import the values from model.js separately.

import { state, loadRecipe } from './model';

Then, you can read the state value after running the loadRecipe() method.

// ...
await loadRecipe(id);
console.log(state.recipe);

But, I think you forget to set recipe value in loadRecipe() function in model.js too.

// get the recipe ...
// then ...
state.recipe = recipe;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading