react query example

김동규·2023년 1월 29일

React 공부하기

목록 보기
6/10
import React, { useEffect, useState } from "react"
import { useMutation, useQuery } from "react-query"
import { Apis } from "./apis/api"

function App() {
  const [textState, setTextState] = useState("");

  const Texthandler = (event) => {
    setTextState(event.target.value)
  }

  const { error, data, isLoading, isError } = useQuery({
    queryKey: ["posts"],
    queryFn: () => Apis.readposts()
  })

  const postMutation = useMutation({
    mutationFn: (body) => Apis.createPost(body)
  })

  if(isLoading) return <div>...loading</div>

  if(isError) return <div>에러!</div>

  return (
    <div className="App">
      <div>
        <input type="text" onChange={Texthandler}/>
        <button type="button" onClick={() => postMutation.mutate({ userId:1, title:"mock", body: textState})}>제출!</button>
      </div>
      <div>
        <h1>포스트 목록!</h1>
        {data.map(each => 
          <div key={each.id}>
            <h2>{each.title}</h2>
            <p>{each.userId}</p>
            <div>{each.body}</div>
          </div>)}
      </div>
    </div>
  )
}

export default App
profile
공식문서를 사랑하는 프론트엔드 주니어 개발자

0개의 댓글