基本上,我在 useEffect() 中有一個 API 請求,因此它會在頁面加載之前加載所有“筆記本”,以便我可以顯示它們。
useEffect(() => { getIdToken().then((idToken) => { const data = getAllNotebooks(idToken); const jsonData = JSON.stringify(data, null, 2); notebooks = JSON.parse(jsonData) as [Notebook, Withdraw[]][]; }); }
如何在我的程式碼中使用此筆記本列表,以便我可以在標籤中使用它?
我是 React 的初學者,所以除了呼叫 useEffect() 中的函數之外,我沒有做太多事情。
更新: 根據要求,這裡是 getAllNotebooks 核心函數、其用例以及 useEffect() 內部呼叫的函數:
withdraw_repository_http
async getAllNotebooks(idToken: string): Promise<[Notebook, Withdraw[]][]> { var notebooks: [Notebook, Withdraw[]][] = [[new Notebook({numSerie : '34000', isActive: false}), [new Withdraw({numSerie : '34000', email: 'erro@maua.br', withdrawTime: Date.now(), finishTime: null})]]]; try { const url = process.env.NEXT_PUBLIC_API_URL + '/get-all-notebooks'; const { data, status} = await axios.get<[Notebook, Withdraw[]][]>(url, {headers : {'Authorization' : `Bearer ${idToken}'`}}); console.log('response status is', status); if (status === 200) { // console.log('response data is', data); const jsondata = JSON.stringify(data, null, 2); notebooks = JSON.parse(jsondata).notebooks as [Notebook, Withdraw[]][]; console.log('notebooks is', notebooks); return notebooks; } else { console.log('response data is', data); } } catch (error) { if (axios.isAxiosError(error)) { console.log('error response is', error); } else { console.log('unknown error'); console.log(error); } } return notebooks; }
get_all_notebooks_usecase
#import { IWithdrawRepository } from '../domain/repositories/withdraw_repository_interface'; export class GetAllNotebooksUsecase { constructor(private withdrawRepo: IWithdrawRepository) {} async execute(idToken: string) { const withdraws = await this.withdrawRepo.getAllNotebooks(idToken); return withdraws; } }
withdraw_provider
async function getAllNotebooks(idToken: string){ try { const notebooks = await getAllNotebooksUsecase.execute(idToken); setNotebooks(notebooks); return notebooks; } catch (error: any) { console.log(`ERROR PROVIDER: ${error}`); const setError = error; setError(setError); return []; } }
希望這對您有所幫助,如有任何疑問,請隨時回答。