Retrieving Information From External Script Using JavaScript

Struggling with exporting/importing script from model.js, I've used the following code:

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

Below is the code snippet from 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);
  }
};

In the rendering part, I'm attempting to access the recipe section 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 encountering an issue trying to access the recipe section here: const { recipe } = model.loadRecipe;

The value returned is undefined. Can you help me pinpoint the problem - whether it's related to importing, exporting, or accessing the data incorrectly? And how should I update the state.recipe with the recipe section?

Thank you for any assistance provided.

Answer №1

If you want to bring in the data from model.js individually, you can do so.

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

After calling the loadRecipe() function, you will be able to access the state variable.

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

However, it seems like you may have overlooked setting the value of recipe within the loadRecipe() function in your model.js as well.

// fetch the recipe data...
// then assign it to state.recipe
state.recipe = recipe;

Answer №2

const myState = {
  currentRecipe: {},
};
console.log(myState.currentRecipe);
const fetchAndLoadRecipe = async function (recipeId) {
  try {
    const response = await fetch(
      `https://forkify-api.herokuapp.com/api/v2/recipes/${recipeId}`
    );
    const recipeData = await response.json();
    if (!response.ok) throw new Error(`${recipeData.message} (${response.status})`);
    console.log(recipeData);
    myState.currentRecipe = recipeData.data.recipe;
    console.log(currentRecipe);
  } catch (error) {
    console.error(error);
  }
};
await fetchAndLoadRecipe(recipeId);
const { currentRecipe } = myState;

I know it might seem strange not returning the data directly from the fetchAndLoadRecipe function, but saving it to a variable gives more flexibility and control over how we manipulate the data later on.

Answer №3

When attempting this with pure JavaScript:

// database.js
const fetchUser = async function (userId) {
    try {
        const response = await fetch(
            `https://users-api.herokuapp.com/api/v2/users/${userId}`
        );
        const userData = await response.json();
        if (!response.ok) throw new Error(`${userData.message} (${response.status})`);
        console.log(userData);
        let { user } = userData.data;
        console.log(user);
    } catch (error) {
        console.error(error);
    }
};

...from a different file (fetchData.js)...

const displayUser = async function () {
    try {
        const userId = window.location.hash.slice(1);
        if (!userId) return;
        showLoader(userContainer);
        // 1. Fetching User Data
        await database.fetchUser(userId);
        const { user } = database.fetchUser.user;
    

...in your HTML document...

<script type="text/javascript" src="database.js"></script> 
<script type="text/javascript" src="fetchData.js"></script> 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enhance the appearance of bootstrap buttons by applying CSS to add shadow and border when the

Working on a frontend project using the React framework and Bootstrap 5.3 for design. Noticing that shadows are deactivated in Bootstrap by default, which means buttons don't display shadows when active as per the Bootstrap v5.0 documentation. Link ...

Using jQuery selectors to assign a value to a particular text input field with a matching name

Is it possible to set only the file name field that matches each file input field? I have three text input fields with the same name and three text fields for the file names. function getFileData(myFile){ var file = myFile.files[0]; var filename = ...

Exploring Nodejs and delving into fundamental queries

As I delved into the world of Nodejs, I quickly realized that my knowledge was limited to just being a user. Transitioning to creating my own server posed challenges that were not easily resolved by online tutorials. This led me here seeking guidance to tr ...

Issue encountered: ENOENT error - The specified file or directory does not exist. This error occurred while attempting to access a directory using the

I don't have much experience with nodejs or express, but I have an API running on http://localhost:3000. One of the endpoints triggers a function that uses the file system to read a file synchronously. However, when I send a post request using Postman ...

Error: Unexpected character found at line 1, position 2 in the JSON data caused a syntax error when parsing

When trying to append this div to another div, I encountered the following error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data This snippet shows my JavaScript code: var str = {'message': message,' ...

Jssor's dynamic slider brings a touch of sophistication to preview upcoming images

Incorporating the jssor nearby slider to create a nearly fullscreen display. The goal is to set the opacity of upcoming images to 0.25 when they are not in the main viewport, giving the edges of the upcoming and previous slides a slight transparency. < ...

Utilize jQuery to dynamically add or remove elements by referencing specific HTML elements

My goal is to dynamically add an element to a dropdown menu and then remove it after selection. I initially attempted to define the htmlElement reference in this way: (Unfortunately, this approach did not work as expected) var selectAnOption = "<option ...

What is the best way to apply a condition within a v-bind in Vue.js?

My Vue component code is as follows: <template> ... <file-pond v-if="this.$route.params.id" label-idle='Drag and drop files here' v-bind:allow-multiple="true" v-bind:req ...

The equivalent of an event listener in event handling

Here is an example of how to set up event listeners: document.getElementById("A").addEventListener("change", function (e) { // do something when A changes }, false) document.getElementById("B").addEventListener("click ...

The react router dom seems to be malfunctioning when attempting to switch between paths

Can anyone help me troubleshoot my React router issue? I'm not seeing any changes when I try to change the path. The code can be found here. .................................... import React from "react"; import Layout from "./Layout"; import Home ...

Interruption of client-side JavaScript by the ASP timer tick event

Exploring the Situation In the realm of web development, I find myself immersed in creating a web application dedicated to monitoring various services. Each service is equipped with an UpdatePanel, showcasing status updates along with interactive buttons ...

Automated pagination in Jquery running seamlessly

I have successfully created pagination using jQuery. Although the script is functioning properly, I now want it to automatically switch between different pages: <script> $(document).ready(function(){ $("#article_load_favourites").load("indexer_favo ...

Unable to display image source in viewport

Currently, I am working on developing a basic ionic app that interacts with an API that I have created. I am encountering an issue where all data is being displayed correctly in the view except for the src attribute of an image. When I use console.log to c ...

Stretching the limits: Combining and expanding your Styled Components theme

I am facing a situation where I have a component library built using Styled Components that has its own theme settings which are not meant to be overridden. Now, I need to incorporate this component library into another project that also uses Style Compone ...

The issue of elements not appearing seems to be related to the passing of parameters to the state

In my AngularJS application, I have a form where users must input an application number. Upon successful entry, the corresponding data should be displayed below. This data can only be accessed through the scope if passed as a parameter to the current state ...

Ways to reduce lag while executing a for loop

How can I optimize my prime number generation process to avoid lagging? For example, is there a way to instantly display the results when generating primes up to 1000? HTML: <!DOCTYPE html> <html> <meta name="viewport" content="width=dev ...

Develop a real-time preview of the form inputs

While working on a multistep form, I am exploring the idea of creating a live preview that shows values entered into different input fields, text areas, and radio buttons. Currently, I have successfully built the form and made some progress using the foll ...

I just installed Electron on my Mac using the command 'sudo npm install electron -g', but now I am encountering an error. How can I resolve this issue

When I first attempted to run the command, I encountered 'Permission Denied' errors so I added sudo before the command as suggested. Another recommendation was to install the electron folder at /usr/local/lib/node_modules, but even after reinstal ...

Utilizing Radio buttons for validation in react-hook-form

After creating a form with radio buttons and implementing validation using React Hook Form, I encountered an issue where the console always displayed "on" regardless of the selected radio button. <div className=""> <label ...

Flipping back and forth between two images within a single HTML file

I am looking to customize my top navbar for two different webpages, the root URL (/) and firstpage (/firstpage). The top navbar contains 2 images that I want to switch based on which page the user is currently on. Here is the code snippet: <img class=" ...