0

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'
Alexander Nied
  • 11,309
  • 4
  • 26
  • 41
  • At a glance you appear to be using an `await` inside of a function that isn't tagged with `async`. I'd be willing to bet if you updated your arrow function with `async` it would resolve the issue. – Alexander Nied May 04 '22 at 03:14

1 Answers1

1
  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();
}, []);
Phil
  • 141,914
  • 21
  • 225
  • 223
Rithick B
  • 161
  • 4