1

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
  • 12,804
  • 4
  • 25
  • 45
Good Panic
  • 117
  • 1
  • 1
  • 6
  • 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

3
  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
  • 157,677
  • 23
  • 242
  • 245
Rithick
  • 236
  • 1
  • 5