M N Tushar
M N Tushar

Reputation: 267

How do use the async function in Es6

I am a beginner learner in react. I want to use async-await in the userEffect hook. But I face a syntext problem and I can't solve it.

code:

useEffect(()=>{
    checkLogin=async()=>{
      await checkUserLogin=()=>{
        if(sessionStorage.getItem('username')==null){
          loggedIn = false
        }
        else{
          loggedIn = true
        }
      }
    }
  })

My error is:

./src/component/my_router.jsx
SyntaxError: /home/mnt/project/react_js/todo-list/src/component/my_router.jsx: Invalid left-hand side in assignment expression. (24:6)

  22 |     console.log(sessionStorage.getItem('username'))
  23 |     checkLogin=async()=>{
> 24 |       await checkUserLogin=()=>{
     |       ^
  25 |         if(sessionStorage.getItem('username')==null){
  26 |           loggedIn = false
  27 |         }

I want to check session storage at the first start of my dom. How do I check it? Please help me...

Upvotes: 0

Views: 817

Answers (6)

Akshay Mathur
Akshay Mathur

Reputation: 501

You can define your function like this:-

useEffect(()=>{
   const chechUserLogin = async() => {
       const checkLogin = () => new Promise((resolve,reject) => {
        if(sessionStorage.getItem('username')==null){
         loggedIn = false;
         reject(loggedIn);
        }
        else{
         loggedIn = true;
         resolve(loggedIn);
        }
       });
     const result = await checkLogin();//checkLogin must return a promise
     //process result
   }
  checkUserLogin();
},[]);

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 202751

./src/component/my_router.jsx
SyntaxError: /home/mnt/project/react_js/todo-list/src/component/my_router.jsx:
Invalid left-hand side in assignment expression. (24:6)

  22 |     console.log(sessionStorage.getItem('username'))
  23 |     checkLogin=async()=>{
> 24 |       await checkUserLogin=()=>{
     |       ^
  25 |         if(sessionStorage.getItem('username')==null){
  26 |           loggedIn = false
  27 |         }

Here it looks like you're trying to do some asynchronous declaration.

await checkUserLogin = () => {

But this OFC isn't valid syntax.

I suspect you meant to declare checkUserLogin as an async function, or you are trying to await the session storage. Since sessionStorage isn't asynchronous there's nothing to wait for, you can simply access the value.

useEffect(() => {
  checkLogin = () => {
    if(sessionStorage.getItem('username') === null){
      loggedIn = false;
    } else{
      loggedIn = true;
    }
  }

  checkLogin();
}, []);

Since checkLogin also doesn't need to wait for asynchronous code you can just place the logic in the useEffect's callback body.

useEffect(() => {
  if(sessionStorage.getItem('username') === null){
    loggedIn = false;
  } else{
    loggedIn = true;
  }
}, []);

Or more succinctly

useEffect(() => {
  loggedIn = !!sessionStorage.getItem('username');
}, []);

Upvotes: 3

M N Tushar
M N Tushar

Reputation: 267

I solve it...

useEffect(()=>{
    const checkLogin=async()=>{
      await (()=>{
        if(sessionStorage.getItem('username')==null){
          loggedIn = false
        }
        else{
          loggedIn = true
        }
      })
    }
  })

Upvotes: 0

Sanoodia
Sanoodia

Reputation: 905

You cannot use directly Async await call in useEffect like this, In order to achieve this approach you have to use it like that.

useEffect(()=>{
    console.log(sessionStorage.getItem('username'))
       async function checkUserLogin() {
          checkLogin()
        }
        checkUserLogin();
  },[])

const checkLogin = async() =>{
 await ()=>{
        if(sessionStorage.getItem('username')==null){
          loggedIn = false
        }
        else{
          loggedIn = true
        }
      }
}

OR like this

useEffect(() => {
    (async() => {
        try {
             await ()=>{
                 if(sessionStorage.getItem('username')==null){
                     loggedIn = false
                  }
                 else{
                     loggedIn = true
                  }
             }
        } catch (e) {
            console.error(e);
        }
    })();
}, []);

Upvotes: 1

Shubham Waje
Shubham Waje

Reputation: 923

You can define and call function in useEffect only

 useEffect(() => {
   const myFunc= async()=> {
      // now you can use await in this
      let response = await fetch('URL')
      response = await response.json()
      dataSet(response)
    }

    myFunc()
  }, [])

Upvotes: 1

Nitsan Cohen
Nitsan Cohen

Reputation: 697

Using async on useEffect itself should be avoided.

Instead you should create your async-await function outside the useEffect hook and then trigger it inside.

Something like this:

const fetchToken = useCallback(async () => {
    let response = await getAccessTokenSilently();
    setToken(response);
  }, [getAccessTokenSilently]);

useEffect(()=>{
 fetchToken()
  },[fetchToken])

Upvotes: 2

Related Questions