Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

Javascript - 모듈과 Class, 로컬스토리지를 활용하여 Board 만들기 ② write의 데이터 저장해서 view에서 보여주기 본문

Javascript

Javascript - 모듈과 Class, 로컬스토리지를 활용하여 Board 만들기 ② write의 데이터 저장해서 view에서 보여주기

보람- 2023. 8. 10. 17:46

목차

1. storage.js에서 저장한 데이터에서 마지막 아이템 가져오기, 초기값 설정하기

2. 게시글 마다 고유한 키값 부여하기 (id)


 

board CRUD
root폴더

 

 

1. storage.js에서 저장한 데이터에서 마지막 아이템 가져오기, 초기값 설정하기

 

★ storage.js

더보기
import {
  INITIAL_STORAGE,
  STORAGE_NAME,
  INITIAL_ID,
  INCREMENT_STEP,
} from "./constants.js";

class Storage {
  name;
  storage;

  constructor(StorageName = STORAGE_NAME) {
    this.name = StorageName; 
    // 'board' : string
    this.storage = localStorage.getItem(this.name); 
    // string(한번이라도 실행하면) | null(실행한적없을때)
  }

  get() {
    if (!this.storage) return INITIAL_STORAGE;
    return JSON.parse(this.storage);
  }

  set(item) {
    const storage = this.get(); // 데이터타입: 객체
    const serialize = JSON.stringify([...storage, item]);
    localStorage.setItem(this.name, serialize);
  }

  // 마지막 아이템 가져오기
  getLatestItem() {
    const latestRow = this.get().pop();
    return latestRow;
  }

  getById(id) {
    return this.get().find((row) => row.id === parseInt(id));
  }

  incrementId() {
    //초기값설정하기
    const row = this.getLatestItem();
    if (!row) return INITIAL_ID;
    return row.id + INCREMENT_STEP;
  }

  clear() {
    localStorage.setItem(this.name, "[]");
  }
}

export default Storage;

 

 

2. 게시글 마다 고유한 키값 부여하기 (id)

 

★ constants.js

더보기
export const INITIAL_STORAGE = [];
export const STORAGE_NAME = "board";
export const INITIAL_ID = 1;
export const INCREMENT_STEP = 1;

★ utils.js

더보기
export const getParams = () => {
  const { search } = window.location;
  if (!search.length) return null;
  return search
    .slice(1)
    .split("&")
    .reduce((acc, param) => {
      const [key, value] = param.split("=");
      acc[key] = value;
      return acc;
    }, {});
};

 

★ write.js

더보기
import BoardRow from "../lib/boardRow.js";
import Storage from "../lib/storage.js";

const storage = new Storage();

const form = document.querySelector("#writeform");

form.addEventListener("submit", (e) => {
  e.preventDefault();

  // form에 감싸서 name의 값만 가져올수있어

  const title = e.target.title.value;
  const writer = e.target.writer.value;
  const content = e.target.content.value;

  // const {
  //   title: { value: title },
  //   writer: { value: writer },
  //   content: { value: content },
  // } = e.target;
  // 구조분해할당 

  // 마지막 아이템 id + 1
  const id = storage.incrementId();

  const dataRow = {
    id: id,
    title: title,
    writer: writer,
    content: content,
  };

  const boardRow = new BoardRow(dataRow);

  storage.set(boardRow);

  console.log("submit!");

  location.href = `/board/view.html?id=${id}`;
});

 

★ view.js

더보기
import { getParams } from "../lib/utils.js";
import Storage from "../lib/storage.js";

try {
  const storage = new Storage();

  const { id } = getParams();
  const row = storage.getById(id);

  const title = document.querySelector("#title");
  const writer = document.querySelector("#writer");
  const content = document.querySelector("#content");

  title.innerHTML = row.title;
  writer.innerHTML = row.writer;
  content.innerHTML = row.content;
} catch (e) {
  console.log(e.message);
  location.href = "./list.html";
}

 

작성한 게시글마다 id를 주기

 


 오늘의 포인트와 남겨두기 ★

 

※ write.js과 view.js 내용 중요함!!!
reduce (배열을 객체로 만들때 사용)

const arr = [1, 2, 3];

const rst = []; // acc=[]
for (let i = 0; i < arr.length; i++) {
  if (arr[i] % 2 === 0) {
    rst.push(arr[i]);
  }
}

// reduce
const aa = arr.reduce((acc, value) => {
  if (value % 2 === 0) acc.push(value);
  return acc;
}, []);

 

*** 앞으로 백엔드, 서버를 배우고 블록체인까지 배워 개발자가 되는 그날까지 화이팅!!!!!!!!!!