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'
>Solution :
- If your want to use "await" keyword inside a function you 1st need to decorate that function with "async" keyword.
- 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();
}, []);