0

Basically, I have an API request in useEffect() so it loads all "notebooks" before the page loads, so I can display them.

useEffect(() => {
   getIdToken().then((idToken) => {
        const data = getAllNotebooks(idToken);
        const jsonData = JSON.stringify(data, null, 2);
        notebooks = JSON.parse(jsonData) as [Notebook, Withdraw[]][];
   });
}

How can I use this notebooks list within my code, so I can use it in a label for example?

I'm a beginner with React, so I didn't manage to do much other than calling the function in the useEffect().

Update: As requested, here is the getAllNotebooks core function, its usecase and the function called inside the 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 [];
    }
  }

1 Answers1

0
const [notebooks, setNotebooks] = useState([]); // initialize notebooks with empty array

useEffect(() => {
   getIdToken().then((idToken) => {
      const data = getAllNotebooks(idToken);
       // I think you don't need this line
       // const jsonData = JSON.stringify(data, null, 2);

      setNotebooks(data);
   });
},[]); // empty brackets here means: useEffect executes only once on load component

// render notebooks using JSX (xml inside javascript)
return {notebooks.map((notebook, index) => {
    <div>
       <h1>My notebook number {index}</h1>
       <h3>This noteboot's name is: {notebook.name}</h3>
       etc..
    </div>
})};

Hope this helps, and any doubt don't hesitate to answer.

Jorge Pérez
  • 234
  • 1
  • 5
  • That should work, but for some reason, the data const is interpreted as void. Is it because getAllNotebooks should have an await? I can send you the async function if needed. Thanks! – Luigi Trevisan May 31 '23 at 02:10
  • I'm not sure what proceeds here, but you could update your question and include the formatted code of the function there. After that we'll help you. :) – Jorge Pérez May 31 '23 at 02:21
  • I've updated the question with more information. – Luigi Trevisan May 31 '23 at 02:29
  • You can't cast an Object as [Notebook, Withdraw[]][]; without a library. Can you please check if this link helps? https://stackoverflow.com/a/40042282/1667803 – Jorge Pérez May 31 '23 at 05:15