skip to Main Content

I have a one reactjs project using axios to post to backend API.

The problem is that I need to wrap 2 axios post in one async function, 1 post is getting bookId and then call another function using the getting bookId to get book details. These 2 functions are in one async function getBookDetails wrapping in useEffect. Both axios Posts will set Authorization token which using Auth0.

After running the project, the first call run successfully, but the 2nd call always get 401 error from backend.

const BookStore = () => {
    useEffect(() => {

     const getBook = async() => {

     const {data: bookId} = await getBookId(name:string)
     const {data: bookDetails} = await getBookDetails(Id:string)
}

getBook()
}
)
}

export function getBookId(name:string) {
return axios.post<string>('url', {name}, {
 headers: {
      "content-type": "application/json",
      Authorization: `Bearer ${token}`
    }
}

export function getBookDetail(id:string) {
return axios.post<string>('url', {id}, {
 headers: {
      "content-type": "application/json",
      Authorization: `Bearer ${token}`
    }
}

2

Answers


  1.  useEffect(() => {
        const getBook = async () => {
          try {
            const name = "exampleBookName";name
            const token = "token";
    
            const bookIdResponse = await getBookId(name, token);
            const bookId = bookIdResponse.data;
    
            const bookDetailsResponse = await getBookDetails(bookId, token);
            const bookDetails = bookDetailsResponse.data;
    
          } catch (error) {
            console.error('Error fetching book data:', error);
          }
        };
    
        getBook();
      }, []);
    

    And make sure to pass the token to the API functions

    export async function getBookId(name, token) {
      return axios.post('url', { name }, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
        }
      });
    }
    
    export async function getBookDetails(id, token) {
      return axios.post('url', { id }, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
        }
      });
    }
    
    Login or Signup to reply.
  2. Instead of use promise all you should go with this

    import React, { useEffect } from 'react';
    import axios, { AxiosResponse } from 'axios';
    
    const BookStore: React.FC = () => {
      const token = 'your_auth_token_here';
    
      useEffect(() => {
        const getBook = async () => {
          try {
            const name = "exampleBookName";
    
            const bookIdResponse: AxiosResponse<string> = await getBookId(name, token);
            const bookId = bookIdResponse.data.id;
    
            const bookDetailsResponse: AxiosResponse<any> = await getBookDetails(bookId, token);
            const bookDetails = bookDetailsResponse.data;
    
            console.log('Book Details:', bookDetails);
          } catch (error) {
            console.error('Error fetching book details:', error);
          }
        };
    
        getBook();
      }, []);
    
      return <div>Book Store</div>;
    };
    
    export default BookStore;
    
    export const getBookId = (name: string, token: string): Promise<AxiosResponse<string>> => {
      return axios.post<string>(
        'url_to_get_bookId',
        { name },
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`,
          },
        }
      );
    };
    
    export const getBookDetails = (id: string, token: string): Promise<AxiosResponse<any>> => {
      return axios.post<any>(
        'url_to_get_bookDetails',
        { id },
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`,
          },
        }
      );
    };
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search