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.
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.
Advertisement
Answer
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;