Skip to content

Commit

Permalink
fix: add missing dependency without causing infinite loop of rerendering
Browse files Browse the repository at this point in the history
  • Loading branch information
olavis committed Nov 11, 2022
1 parent fd40ccb commit 8f5c01d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
14 changes: 14 additions & 0 deletions web/src/hooks/useTodoAPI.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useContext, useEffect, useState } from 'react'
import { AuthContext } from 'react-oauth2-code-pkce'
import TodoAPI from '../api/TodoAPI'

export function useTodoAPI() {
const { token } = useContext(AuthContext)
const [todoAPI, setTodoAPI] = useState<TodoAPI>(new TodoAPI(token))

useEffect(() => {
setTodoAPI(new TodoAPI(token))
}, [token])

return todoAPI
}
10 changes: 4 additions & 6 deletions web/src/hooks/useTodos.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { useEffect, useContext, useState } from 'react'
import { AuthContext } from 'react-oauth2-code-pkce'
import TodoAPI from '../api/TodoAPI'
import { useEffect, useState } from 'react'
import { AxiosError } from 'axios'
import { AddTodoResponse, ErrorResponse } from '../api/generated'
import { useTodoAPI } from './useTodoAPI'

const useTodos = (): {
todos: AddTodoResponse[]
Expand All @@ -15,8 +14,7 @@ const useTodos = (): {
const [todos, setTodos] = useState<AddTodoResponse[]>([])
const [isLoading, setLoading] = useState<boolean>(true)
const [error, setError] = useState<AxiosError<ErrorResponse> | null>(null)
const { token } = useContext(AuthContext)
const todoAPI = new TodoAPI(token)
const todoAPI = useTodoAPI()

useEffect(() => {
setLoading(true)
Expand All @@ -25,7 +23,7 @@ const useTodos = (): {
.then((response) => setTodos(response.data))
.catch((error: AxiosError<ErrorResponse>) => setError(error))
.finally(() => setLoading(false))
}, [])
}, [todoAPI])

const addItem = (title: string) => {
setLoading(true)
Expand Down

0 comments on commit 8f5c01d

Please sign in to comment.