-2

We have an ReactJS App, and want to validate saved JWT Token at API end. For that adding await axiosClient.post("${URL}/AuthenticateUser/ValidateToken") in App.tsx, it's throwing an error.

index.tsx:

const msalInstance = new PublicClientApplication(msalConfig);
const container = document.getElementById('root');
const root = createRoot(container!);

root.render(
  <MsalProvider instance={msalInstance}>
    <App />
  </MsalProvider>,
);

module.hot?.accept();

App.tsx:

async function App() {
let isAuthenticated = false;
  const url = `${URL}/AuthenticateUser/ValidateToken`;

  if (localStorage.getItem('token')) {
    await axiosClient.post(url).then((result) => {
      /* Do Something */
    });
}

axiosClient.tsx:

export const axiosClient = axios.create({
  baseURL: URL,
  timeout: 300000,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Authorization: `Bearer ${getToken()}`,
  },
});

enter image description here

Error:

TS2786: 'App' cannot be used as a JSX component.
Its return type 'Promise<Element>' is not a valid JSX element.
6
  • 2
    Does this answer your question? Using async/await inside a React functional component Commented Feb 27, 2023 at 18:57
  • Or this or this or... Commented Feb 27, 2023 at 18:58
  • 1
    @JaredSmith 300000 milliseconds is 5 minutes Commented Feb 27, 2023 at 19:16
  • Refer below answer, that seems similar to this question: stackoverflow.com/questions/57847626/… Commented Feb 28, 2023 at 5:27
  • @JaredSmith Now we are getting below error. Error: Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: Commented Feb 28, 2023 at 7:50

1 Answer 1

0

You should not be adding the async keyword to the React component itself. Instead you should do something like this

function App() {
  const [isAuthenticated, setIsAuthenticated] = React.useState(false);
  React.useEffect(() => {
    const getToken = async () => {
      const url = `${URL}/AuthenticateUser/ValidateToken`;

      if (localStorage.getItem('token')) {
        await axiosClient.post(url).then(result => {
          /* Do Something */

          //Set this wherever you need it
          setIsAuthenticated(true);
        });
      }
    };
    getToken();
  }, []);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Now we are getting below error. Error: Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
Can you show the code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.