Home  >  Q&A  >  body text

Using variables loaded via API requests in useEffect() within a React container

Basically, I have an API request in useEffect() so it loads all the "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 do I use this notebook list in my code so that I can use it in tags?

I'm a beginner in React, so I didn't do much other than calling functions in useEffect().

renew: As requested, here is the getAllNotebooks core function, its use case, and the function called internally by 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 [];
    }
  }

P粉663883862P粉663883862420 days ago556

reply all(1)I'll reply

  • P粉311089279

    P粉3110892792023-09-16 00:47:40

    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, if you have any questions please feel free to answer.

    reply
    0
  • Cancelreply