Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

UseEffect Unexpected Reserved Word 'await'

I’m trying to convert my class component to a function component. I believe instead of ComponentDidMount we need to use useEffect:

useEffect(() => {
  const {
    data: ServerResponse
  } = await axios.get('http://127.0.0.1:8000/api/tweets/')
  console.log(ServerResponse)

  setPosts(ServerResponse)

}, [])

But I get the following error:

Unexpected reserved word 'await'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. If your want to use "await" keyword inside a function you 1st need to decorate that function with "async" keyword.
  2. But useEffect hook doesn’t expect a promise to be returned from the callback we pass to it.

Solution:

useEffect(() => {
  const getData = async () => {
    const { data: ServerResponse } = await axios.get(
      "http://127.0.0.1:8000/api/tweets/"
    );
    console.log(ServerResponse);

    setPosts(ServerResponse);
  };
  getData();
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading