TIL DAY.23 React.Mock Data 활용법

Dan·2020년 9월 9일
0

리액트

목록 보기
5/17

프론트엔드 개발자는 백엔드로부터 API가 나오지 않더라도 mock data, 즉 가짜 데이터를 만들어서 미리 내가 만든 화면에서 데이터가 어떻게 나타나는지 테스트하며 개발을 진행 할 수 있습니다.

Mock data

1-1. mock data란?

  • 실제 API에서 받아온 데이터가 아닌 프론트엔드 개발자가 필요에 의해 샘플로 만들어본 데이터를 말합니다.

1-2. mock data가 필요한 이유

  • 배열 데이터에 Array.map() 함수를 적용해서 UI를 구현할 수 있습니다.
  • API 아직 준비중인 경우 : 백엔드에서 API가 나올 때까지 무작정 기다리는게 아니라, mock data를 만들어 데이터가 들어오는 상황을 미리 대비하고 UI가 기획에 맞게 구현되는지 먼저 확인해야 합니다.

mock data 관리하는 두 가지 방법

2-1. data.js

  • 첫번째 방법은 .js파일로 데이터를 분리하는 방법입니다,배열 데이터를 변수에 담고 필요한 컴포넌트에서 import해서 사용합니다. .js 파일은 데이터를 import하는 컴포넌트 바로 옆으로 접근하기 쉬운 곳에 생성합니다.

1)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;

2)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-2. data.json

  • 두 번째는 실제 API에서 보내주는 데이터 형식에 맞게 json 파일에 데이터를 담아 fetch 함수를 사용해 데이터를 받아오는 방법입니다.
  • data.json위치 - public폴더 > 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
    }
  ]
}
  • 해당 데이터는 http://localhost:3000/data/data.json 주소를 입력해 확인해 볼 수 있습니다.

  • 해당 주소를 API 주소로 생각하고 fetch 함수와 http GET method 를 사용해 실제 API에서 데이터를 받아오는 것처럼 코드를 작성합니다.

  • 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
만들고 싶은게 많은 개발자

0개의 댓글