MSW 와 React-Query - 2

hojoon·2023년 8월 8일
0

리액트

목록 보기
8/10

useQuery

  • A unique key for the query (유니크하다)
  • A function that returns a promise that:
    - Resolves the data, or
    - Throws an error

    프로미스다.

Query Keys

  • Array keys (배열이다.)
  • 배열의 첫번째 인자로 들어간다는 뜻
useQuery(['todo', 5], ...)
// queryKey === ['todo', 5]

// An individual todo in a "preview" format
useQuery(['todo', 5, { preview: true }], ...)
// queryKey === ['todo', 5, { preview: true }]

// A list of todos that are "done"
useQuery(['todos', { type: 'done' }], ...)
// queryKey === ['todos', { type: 'done' }

이렇게도 가능하다.!!

객체는 하나로 다 인지된다.

useQuery(['todos', { status, page }], ...)
useQuery(['todos', { page, status }], ...)
useQuery(['todos', { page, status, other: undefined }], ...)-

배열자체를 다르게 넣으면 다르게 인지한다.

The following query keys, however, are not equal. Array item order matters!

useQuery(['todos', status, page], ...)
useQuery(['todos', page, status], ...)
useQuery(['todos', undefined, page, status], ...)

Query function

전달하는 값도 그대로 줄 수 있음

useQuery(['todos'], fetchAllTodos)
useQuery(['todos', todoId], () => fetchTodoById(todoId))
useQuery(['todos', todoId], async () => {
  const data = await fetchTodoById(todoId)
  return data
})
useQuery(['todos', todoId], ({ queryKey }) => fetchTodoById(queryKey[1]))
  • 이게 다 같다는 거임
  • 어떻게 꺼내서 쓰는지만 다를뿐

Parallel Queries

  • 병렬 수행
function App () {
  // The following queries will execute in parallel
  const usersQuery = useQuery('users', fetchUsers)
  const teamsQuery = useQuery('teams', fetchTeams)
  const projectsQuery = useQuery('projects', fetchProjects)
  ...
}
  • suspense를 사용하면 제대로 동작안할수 있다. 왜냐하면 하나라도 요청중이면 suspense가 동작하는데 그렇기 때문에 다른 쿼리가 제대로 동작안할수 있다. 그래서 usequeries를 써라!
function App({ users }) {
  const userQueries = useQueries(
    users.map(user => {
      return {
        queryKey: ['user', user.id],
        queryFn: () => fetchUserById(user.id),
      }
    })
  )
}

Dependent Queries

const { data: user } = useQuery(['user', email], getUserByEmail)

const userId = user?.id

// Then get the user's projects
const { isIdle, data: projects } = useQuery(
  ['projects', userId],
  getProjectsByUser,
  {
    // The query will not execute until the userId exists
    enabled: !!userId,
  }
)

응답이 있다면 userid
값이 있는 상황에서만 실행하고 싶다면

몰랐던거

자바스크립트에서 느낌표두개(!!)는 다른 타입의 데이터를 boolean 타입으로 명시적으로 형 변환(Type Conversion)하기 위해 사용
코드에서 왜 굳이 !! 두개를 할까 생각했는데 명시적으로 true로 변환하기 위해서

Background Fetching Indicators

  • 페칭을 뒤에서 하고 있을 때 , 명시적이지 않을때 (포커싱이나 다시 호출할 때)

Displaying Global Background Fetching Loading State

글로벌 인디케이터
useIsfethcing 쿼리중에 어떤것이라도 페칭되고 있다면 값을 가져옴

refetchOnWindowFocus

Query retries

  • Setting retry = false will disable retries.
  • Setting retry = 6 will retry failing requests 6 times before showing the - final error thrown by the function.
  • Setting retry = true will infinitely retry failing requests.
  • Setting retry = (failureCount, error) => ... allows for custom logic based on why the request failed.

Retry Delay

몇번만에 재시도할래? 디폴트는 1초 최대는 30초 !

정리

profile
프론트? 백? 초보 개발자의 기록 공간

0개의 댓글