Home > Mobile >  Using useEffect with Axios & Await
Using useEffect with Axios & Await

Time:08-10

I'm having an issue getting my "topic" state to update when using Axios. At first I thought useEffect wasn't being called but when I put a simple useEffect(() => setTopic("Test")) in it worked fine. So somehow I believe the await is messing me up.

The issue: When the useEffect below is called the page requires a refresh to show the updated state.

What can I do to update the state correctly and show it without a page refresh?

useEffect(async () => {
const result = await axios({
method: "GET",
withCredentials: true,
url: "http://localhost:4000/userData",
}).then((res) => {
setTopic(res.data.topic);
});
}, [])

CodePudding user response:

The callback function inside a useEffect can't be async

What you can do rather is to call an async function from within useEffect which will do the things for you. Here is an example:

const fetchUserData = async () => {
    const result = await axios({
        method: "GET",
        withCredentials: true,
        url: "http://localhost:4000/userData",
    }).then((res) => {
        setTopic(res.data.topic);
    });
};    

useEffect(() => {
    fetchUserData();
}, [])

CodePudding user response:

Try this

async function runThis() {
  const result = await axios({
    method: "GET",
    withCredentials: true, 
    url: "http://localhost:4000/userData",
 }).then((res) => {
  setTopic(res.data.topic);
 }); 
}

useEffect(
   runThis();
}, [])
  • Related