DEV Community

Discussion on: Create an awesome JS API interface using Fetch (in less than 50 lines)

Collapse
 
wagnerfillio profile image
Wagner Fillio • Edited

Hello!

Suppose I create a BookController and have a function below in this controller:


import Fetch from './Fetch.js';

// GET
async function getAllBooks() {
  const books = await Fetch.get('/books');
}

Could I export this function to call it in another js file?


function getAll() {   
  return getAllBooks();
}

export default {
  getAll,
};

Another thing, is it possible to make the constant books a global variable and export that variable so that I can use it anywhere?

Collapse
 
eaich profile image
Eddie

Yes, you can export it. Regarding global access, I like to create a new module for that. In my case, I called it Store.

// Store.js
const Store = {};
export default Store;

I then include this in my modules whenever I need to access a global variable.

import Store from './Store.js';

export async function getAllBooks() {
  const books = await Fetch.get('/books');
  Store.BOOKS = books;
  return books;
}
Collapse
 
wagnerfillio profile image
Wagner Fillio • Edited

thanks for the return, it was of great help!

Just one more question and I will always be grateful!

Suppose I require the data from bookId = 1 and want to display the attribute data in a Modal component (we can imagine the bootstrap), I would also like to change any value of any field, imagine the title of the book and save next.

In the code below, I'm just giving you an idea! Can you help me organize this code?


function openModal() {
    $("#form").modal({show: true});
}

function objectForm() {
    const id = document.getElementById('id');
    const title = document.getElementById('title');
    const author = document.getElementById('author');

    id.value = Store.BOOK.id;
    title.value = Store.BOOK.title;
    author.value = Store.BOOK.author;
}

// use to save start
// function called by the save button
function saveBook() {
    formObject();    
}

function formObject() {
    const id = document.getElementById('id');
    const title = document.getElementById('title');
    const author = document.getElementById('author');

    Store.BOOK.id = id.value;
    Store.BOOK.title = title.value;
    Store.BOOK.author = author.value;
}
// // use to save end

// GET BY ID
async function getBookById(bookId) {
    const book = await Fetch.get('/books/' + bookId);
    Store.BOOK = book;
    //return book;
    objectForm();
    openModal();
}