데이터 통신에 대해 알아보기

SongNoin·2021년 9월 4일
0
post-thumbnail

동기/ 비동기 통신(서버와 데이터를 주고 받는 방식)

📔 동기

  • 서버 컴퓨터가 작업이 끝날 때까지 기다리는 통신

  • 한 번에 하나씩 통신

  • 응답이 모두 끝난후 요청

📔 비동기

  • 서버컴퓨터가 작업이 끝날 때까지 기다리지 않는 통신

  • 서버에 요청(등록, 수정, 삭제 등) 저장이 될 때까지 기다리지 않고 다른 작업 진행

  • 오래걸리는 일 ( 이메일 전송하기 , 게임 다운 받으면서 카톡하는 경우)

  • 동시에 여러개 작업

📔비동기를 동기로 바꾸주는 명령어

  • async / await
//비동기 통신
async function aaa(){
	//서버 컴퓨터에 요청하는 코드
}
//동기 통신
async function bbb(){
	await//서버 컴퓨터에 요청하는 코드
}
// 비동기통신
async function aaa(){
  const data = axios.get('https://koreanjson.com/posts/1')
  cosnlole.log(data)
	// Promise
}
//동기 통신
async function bbb(){
  const data = await axios.get('https://koreanjson.com/posts/1')
  cosnlole.log(data)
    //{id:1, title:"정당의.."}
}

📔 Promise

  • 프로미스는 자바스크립트 비동기 처리에 사용되는 객체

  • API가 실행되면 서버에다가 요청을 보내는데 받아오기도 전에 화면에 데이터를 표시하려고하면 오류가 발생하거나 빈화면이 뜸
    -> (이런 문제점을 해결하기위한 방법이 Promise)

REST axios vs GRAPLQL apllo

  • REST axios 는 설치만 하면 사용가능

  • GRAPLQL apollo 는 app.js 에서 세팅까지 해줘야함

  • const [실행함수 ] = useMutation(CREATE_BOARD)

오타 체크하는방법

단어 더블클릭 -> 전체에서 같은 단어들이 모두 영역이 쳐짐

개발자모드 - network

📔 backend 로 통신이 잘됐는지 확인하는 방법

  • Headers 에서 어떤값을 보냈는지 확인
  • Preview 에서 간략적인 응답 확인
  • Response 에서 응답메시지 확인

자유게시판 게시물등록 (mutataion)

📔 게시물 등록 창 입력

📔 게시물 등록 조회

💻 먼저 app.js 에 graphql 주소를 연결해준다.

import '../styles/globals.css'
import { ApolloClient, ApolloProvider, 
        InMemoryCache } from '@apollo/client'
function MyApp({ Component, pageProps }) {
  const client = new ApolloClient({
    uri: "http://backend03.codebootcamp.co.kr/graphql",
    cache: new InMemoryCache()
  })
  return (
    <ApolloProvider client={client}>
      <Component {...pageProps} />
    </ApolloProvider>
  )
}
export default MyApp

💻 js / html

import { useMutation, gql } from "@apollo/client";
const CREATE_BOARD = gql`
  mutation createBoard($createBoardInput: CreateBoardInput!) {
    createBoard(createBoardInput: $createBoardInput) {
      _id
    }
  }
`;
export default function BoardsNewPage() {
  const [createBoard] = useMutation(CREATE_BOARD);
  // const [실행함수 ] = useMutation(CREATE_BOARD)
  async function onClickCorrect() {
    try {
      const result = await createBoard({
        // network 창에 뜨는 graphql 과 짝궁 
        // (여기서 graphql 창이 생김)
        variables: {
          createBoardInput: {
            writer: myWriter, 
            //이름을 동일하게 줄수도 있음  [키와 밸류가 같으면 생략가능!] 
            //ex) writer, 하고 넘어가도 됨
            password: myPassword,
            title: myTitle,
            contents: myContents,
          },
        },
      });
      console.log(result.data.createBoard._id);
    } catch (error) {
      console.log(error);
    }
  return (
    );
}

💻 중요포인트

  • useMutation, gql기능을 쓰기위한 import
import { useMutation, gql } from "@apollo/client";
  • mutation
const CREATE_BOARD = gql`
  mutation createBoard($createBoardInput: CreateBoardInput!) {
    createBoard(createBoardInput: $createBoardInput) {
      _id
    }
  }
`;
// graphql api를 통해 mutation 하기 
  • const [실행함수 ] = useMutation(상수)
const [createBoard] = useMutation(CREATE_BOARD);
  • 동기통신
async function onClickCorrect() {
  const result = await createBoard
  // async / await 를 사용해 동기통신하기
  • graphql 뮤테이션에 try ~ catch 적용
try { //graphql 뮤테이션
  } catch (error) {
      console.log(error); // 경고창(실패했습니다.)  
    			  // ==>  백엔드 개발자가 보내주는 실패 메시지

0개의 댓글