From 8f5c01d5141c4dbd4ac9b99ebc39ae10f378147f Mon Sep 17 00:00:00 2001 From: Olava Faksdal <38139899+olavis@users.noreply.github.com> Date: Thu, 10 Nov 2022 15:58:12 +0100 Subject: [PATCH] fix: add missing dependency without causing infinite loop of rerendering --- web/src/hooks/useTodoAPI.tsx | 14 ++++++++++++++ web/src/hooks/useTodos.tsx | 10 ++++------ 2 files changed, 18 insertions(+), 6 deletions(-) create mode 100644 web/src/hooks/useTodoAPI.tsx diff --git a/web/src/hooks/useTodoAPI.tsx b/web/src/hooks/useTodoAPI.tsx new file mode 100644 index 00000000..a3b1f275 --- /dev/null +++ b/web/src/hooks/useTodoAPI.tsx @@ -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(new TodoAPI(token)) + + useEffect(() => { + setTodoAPI(new TodoAPI(token)) + }, [token]) + + return todoAPI +} diff --git a/web/src/hooks/useTodos.tsx b/web/src/hooks/useTodos.tsx index b1e092a3..b7d22ab1 100644 --- a/web/src/hooks/useTodos.tsx +++ b/web/src/hooks/useTodos.tsx @@ -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[] @@ -15,8 +14,7 @@ const useTodos = (): { const [todos, setTodos] = useState([]) const [isLoading, setLoading] = useState(true) const [error, setError] = useState | null>(null) - const { token } = useContext(AuthContext) - const todoAPI = new TodoAPI(token) + const todoAPI = useTodoAPI() useEffect(() => { setLoading(true) @@ -25,7 +23,7 @@ const useTodos = (): { .then((response) => setTodos(response.data)) .catch((error: AxiosError) => setError(error)) .finally(() => setLoading(false)) - }, []) + }, [todoAPI]) const addItem = (title: string) => { setLoading(true)