vscode에서 graphql 사용하기

OwlSuri·2022년 3월 17일
0

setting

설치

apolloclient/graphql - npm install @apollo/client graphql

app.js 설정

import '../styles/globals.css'
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client'

function MyApp({ Component, pageProps }) {

  const client = new ApolloClient({
    uri: "  url  ", 
    cache: new InMemoryCache()
  })

  return (
  <ApolloProvider client={client}>
    <Component {...pageProps} />
  </ApolloProvider>
  )
}

export default MyApp

gragpql 사용하기

const [ 실행함수 ] = useMutation
ex) const [ 실행함수 ] = useMutation(CREATE BOARD)
- 실행함수() 로 실행

import { useMutation, gql } from '@apollo/client'
import {useState} from 'react'

const CREAT_BOARD = gql`
        mutation mymutation
        ($writer: String, $title:String , $contents: String){

            createBoard(writer:$writer, title:$title, contents:$contents){
                _id
                number
                message
            }
        }
`
export default function GraphqlMutationPage(){
    const [data, setData] = useState("")

    const [writer, setWriter] = useState("")
    const [title, setTitle] = useState("")
    const [contents, setContents] = useState("")

    const [callApi] = useMutation(CREAT_BOARD)

    const callGraphqlAPI = async () =>{
        const result = await callApi({
            variables: {writer: writer, title: title, contents: contents}
        }) //graphql방식
        console.log(result)
        setData(result.data.createBoard.message)
        // setData(result.data.title)
    }

    const onChangeWriter = (event) => {
        setWriter(event.target.value)
    }

    const onChangeTitle = (event) => {
        setTitle(event.target.value)
    }

    const onChangeContents = (event) => {
        setContents(event.target.value)
    }

    return(
    <div>
        {/* <div>{data}</div> */}
        작성자 : <input type={'text'} onChange={onChangeWriter}/><br/>
        제목 : <input type={'text'} onChange={onChangeTitle}/><br/>
        내용 : <input type={'text'} onChange={onChangeContents}/><br/>
        {data}<br/>
        <button onClick={callGraphqlAPI}>GRAPHQL_API요청하기!</button>
    </div>
    ) 
}

profile
기억이 안되면, 기록을 -

0개의 댓글