본문 바로가기
✘✘✘ 개발일기

[Vanilla][Javascript] 기본들

by PrettyLog 2022. 11. 13.

API 호출

// fetch api module
const HOST = "";
export const request = async (path, options = {}) => {
  try {
    const uri = `${HOST}/${path}`;
    const response = await fetch(uri, options);

    if (response.ok !== true) {
      throw new Error("API failed");
    }

    const json = await response.json();
    return json;
  } catch (e) {
    alert(e.message);
  }
};

Index

// index.js
const app = new App({
  $target: document.querySelector("#app"),
});
app.init();
console.log('App mounted:: ', app);

App

// App.js
function App($target) {
    $target.innerHTML = '';
    this.state = {
        data: []
    };

    this.setState = (nextState) => {
        this.state = nextState;
        page.setState({
            ...page.state,
            pData: this.state.pData
        });
    }

    const page = new Page({
        $target,
        initialState: {

        },
        onClick: (e) => {
            // function
        }
    });

    this.

    this.init = async () => {
        try {
            // fetch initial data
        } catch(e) {

        }
    }
}

Page

function Page({ $target, initialState = {}, onClick, classList = [] }) {
    this.$dom = document.createElement('div');
    this.state = initialState;
    this.$dom.classList.add(...classList);
    this.$dom.classList.remove(...classList);
    this.$dom.classList.toggle('name');

    $target.appendChild(this.$dom);

    this.setState = nextState => {
        this.state = nextState;
        this.render(); // change content when state changes
    }

    const renderList = (items = []) => {
        return this.items.map((item, idx) => {
            return `<div>${idx}</div>`;
        }).join('');
    }

    this.render = () => {
        this.$target.innerHTML = `<div>${renderList(this.state.items)}</div>`;
    }

    this.render(); // initiate here? or App
}

LocalStorage 모듈

// local storage => empty => null
function setLocalItem({ key, value }) {
    value = JSON.stringify(value);
    window.localStorage.setItem(key, value);
    console.log('local set get: ', key, getLocalItem(key));

}

function getLocalItem(key) {
    const value = window.localStorage.getItem(key);
    console.log('local item get: ', key, value);
    if (value === null) {
        throw new Error(`${key} does not have value: LOCAL`);
    }
    return JSON.parse(value);
}

function removeLocalItem(key) {
    window.localStorage.removeItem(key);
    console.log('local item removed: key:: ', key, getLocalItem(key));
}

댓글