미라클 메모리api로 데이터를 요청하여 받아오는 연습을 하고싶다. api연습을 하기 위해서 서버 까지 직접 구축하는것은 굉장히 시간이 오래걸리는 일이다. 이럴때는 누군가가 만들어놓은 가상 서버에서 데이터를 요청해보는 연습을 하는게 가장 효율적이라고 생각한다. JSONPlaceholder는 유명한 가상 서버 API를 제공한다


다양한 데이터가 있겠지만 그중에서도 /comments 를 사용해서 일기장에 적을 만한 데이터를 불러올 예정이다.

const getData = async () => {
const res = await fetch(
"<https://jsonplaceholder.typicode.com/comments>"
).then((res) => res.json());
};
fetch 함수를 잘 활용하면 서버에서 데이터를 잘 요청할 수 있다. fetch 메서드는 ES6에 추가된 프로미스 기반의 내장 API 라이브러리이다. 그렇기에 fetch함수를 통해 반환된 Promise 객체에 후속처리 메서드를 더하여 데이터 패칭에 성공했을 때의 값을 매개변수로 받아온다. 이어서 async await을 하여 비동기로 요청한 데이터에 순서를 보장해준다. 불러온 데이터는 아래와 같다.


const getData = async () => {
const res = await fetch(
"<https://jsonplaceholder.typicode.com/comments>"
).then((res) => res.json());
const initData = res.slice(0, 20).map((it) => {
return {
author: it.email,
content: it.body,
emotion: Math.floor(Math.random() * 5) + 1,
created_date: new Date().getTime(),
id: dataId.current++,
};
});
setDate(initData);
};
fetch 한 데이터를 가공한다 먼저 slice 함수를 사용한다. 왜 slice 함수를 사용할까? slice함수를 사용하면 첫번째 인자부터 두번째 인자까지의 배열을 잘라서 새로운 배열을 만들 수 있다.
Array.prototype.slice() - JavaScript | MDN
slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// 0~2번째 요소를 없애버린다
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// 3번째 요소부터 4번째 요소까지 불러온다.
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// 2번째 요소부터 4번째 요소까지 불러온다
// expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// 마지막 2번째로 부터 요소를 불러온다.
// expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// 마지막 1번째로 부터 2개의 요소를 불러온다.
// expected output: Array ["camel", "duck"]
console.log(animals.slice());
// 원본과 일치하는 새로운 객체를 반환한다.
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]