Categories
React Answers

How to Fix the “‘await’ has no effect on the type of this expression” warning in React?

Spread the love

Sometimes, we may run into the "’await’ has no effect on the type of this expression" warning in React.

In this article, we’ll look at how to fix the "’await’ has no effect on the type of this expression" warning in React.

Fix the "’await’ has no effect on the type of this expression" warning in React

To fix the "’await’ has no effect on the type of this expression" warning in React, we should make sure that we only use await on expressions that returns a promise.

For instance, we write:

import React, { useEffect, useState } from "react";

const fetchAnswer = async () => {
  const response = await fetch(`https://yesno.wtf/api`);
  const json = await response.json();
  return json;
};

export default function App() {
  const [ans, setAns] = useState();

  useEffect(() => {
    const getAnswer = async () => {
      const { answer } = await fetchAnswer();
      setAns(answer);
    };
    getAnswer();
  }, []);

  return (
    <>
      <div>{ans}</div>
    </>
  );
}

to clear the warning.

We have fetchAnswer function that makes a GET request with fetch.

Then we return the JSON response from the API by calling response.json and get the resolved value with await.

Then we return the json.

Next, we use the JSON response data in the getAnswer function.

It calls fetchAnswer to return a promise with the JSON response data.

And then we call serAns with the resolved value that we get with await.

Finally, we display the ans value on the screen by returning it.

Conclusion

To fix the "’await’ has no effect on the type of this expression" warning in React, we should make sure that we only use await on expressions that returns a promise.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *