React - Mock data

Enjoywater·2020년 9월 19일
0

TIL

목록 보기
21/33
post-thumbnail

Mock data

API가 나오기 전에 Front-end에서 전송받을 데이터를 미리 가짜로 만들어서 개발을 진행할 수 있다.
미리 가짜데이터API로 부터 받을 데이터같은 구조로 만들어서 개발을 진행하면,
실제 API가 들어올때 수월하게 작업을 할 수 있다.
--.js / --.json 2가지 방식으로 만들 수 있다.

1. data.js

--.js로 data를 만들면 배열 데이터변수에 담고 import해서 사용해야 한다.
파일의 위치는 import하는 컴포넌트 바로 옆으로 접근하기 쉬운 곳에 생성한다.

// data.js
const COMMENT = [
  {
    id: 1,
    userName: 'wecode',
    content: 'Welcome to world best coding bootcamp!',
    isLiked: true
  },
  {
    id: 2,
    userName: 'joonsikyang',
    content: 'Hi there.',
    isLiked: false
  },
  {
    id: 3,
    userName: 'jayPark',
    content: 'Hey.',
    isLiked: false
  }
];

export default COMMENT;
// Comment.js
import React, { Component } from 'react';
import CommentList from './CommentList/CommentList';
import COMMENT from './commentData';
import './Comment.scss';

class Comment extends Component {
  constructor() {
    super();
    this.state = {
      commentList: [],
      commentValue: ''
    };
  }

  componentDidMount() {
    this.setState({
      commentList: COMMENT
    });
  }

  handleCommentValue = e => {
    this.setState({
      commentValue: e.target.value
    });
  };

	addComment = e => {
    e.preventDefault();
    const { commentList, commentValue } = this.state;
    this.setState({
      commentList: [
        ...commentList,
        {
          id: commentList.length + 1,
          userName: 'wecode',
          content: commentValue,
          isLiked: false
        }
      ],
      commentValue: ''
    });
  };

render() {
    const { commentList, commentValue } = this.state;

    return (
      <div className="comment">
        <h1>Main Page</h1>
        <ul>
          {commentList.map(comment => {
            return (
              <CommentList
                clickEvent={this.changeColor}
                name={comment.userName}
                comment={comment.content}
              />
            );
          })}
        </ul>
        <div className="commentInput">
          <form onSubmit={this.addComment}>
            <input
              onChange={this.handleCommentValue}
              type="text"
              placeholder="enter comment"
              value={commentValue}
            />
          </form>
          <button className="addCommentBtn" onClick={this.addComment}>
            Click
          </button>
        </div>
      </div>
    );
  }
}

export default Comment;

2. data.json

--.json형식의 파일은 실제 API에서 보내주는 형식에 맞게 작성하고, fetch()를 통해 받아온다.
파일의 위치는 public폴더 속, data폴더에 위치시킨다.

작성한 데이터는 http://localhost:3000/data/data.json 주소를 입력하여 확인해볼 수 있다.

// data.json
{
  "data": [
    {
      "id": 1,
      "userName": "wecode",
      "content": "Welcome to world best coding bootcamp!",
      "isLiked": true
    },
    {
      "id": 2,
      "userName": "joonsikyang",
      "content": "Hi there.",
      "isLiked": false
    },
    {
      "id": 3,
      "userName": "jayPark",
      "content": "Hey.",
      "isLiked": false
    }
  ]
}
// App.js

import React, { Component } from 'react';
import CommentList from './CommentList/CommentList';
import './Comment.scss';

class Comment extends Component {
  constructor() {
    super();
    this.state = {
      commentList: [],
      commentValue: ''
    };
  }

  componentDidMount() {
    fetch('http://localhost:3000/data/commentData.json', {
      method: 'GET'
    })
      .then(res => res.json())
      .then(res => {
        this.setState({
          commentList: res.data
        });
      });
  }

 render() {
    const { commentList, commentValue } = this.state;

    return (
      <div className="comment">
        <h1>Main Page</h1>
        <ul>
          {commentList.map(comment => {
            return (
              <CommentList
                clickEvent={this.changeColor}
                name={comment.userName}
                comment={comment.content}
              />
            );
          })}
        </ul>
        <div className="commentInput">
          <form onSubmit={this.addComment}>
            <input
              onChange={this.handleCommentValue}
              type="text"
              placeholder="enter comment"
              value={commentValue}
            />
          </form>
          <button className="addCommentBtn" onClick={this.addComment}>
            Click
          </button>
        </div>
      </div>
    );
  }
}

export default Comment;
profile
블로그 이전 👉🏻 enjoywater.tistory.com

0개의 댓글