Hamid Ashoor
Hamid Ashoor

Reputation: 33

how to pass function variable by return function() in js

I've worked with react native and I have a problem...

const SignIn = () => {
    screensplash()
    fetch('http://api.megamouj.ir/api/v1/logincheck/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username,
        password: password
      })
    })
      .then((response) => response.json())
      .then((responseJson) => {
        login(responseJson.token).then(
          (token) => {
            setToken(token)

            getMoviesFromApiAsync()
          }
      
        )
      })
  }

and when program goes on

login(responseJson.token)

I faced this error:

Possible Unhandled Promise Rejection (id: 0): TypeError: Cannot read property 'then' of undefined

and this is my login() function:

  const login = (token) => {
    setLoading(true)

    AsyncStorage.setItem('token', token, (error) => {
      if (token == 'wrong') {
        setIsLoggedIn(false)
        setLoading(false)
        ToastAndroid.show(
          'error',
          ToastAndroid.SHORT
        )
      } else if (!error) {
        setIsLoggedIn(true)
        setLoading(false)
      }
    })
    return token   }

help me please!

Upvotes: 2

Views: 103

Answers (1)

user15388024
user15388024

Reputation:

You can use async/await to handle the promise returned from AsyncStorage.setItem and return a promise containing token:

const login = async (token) => {
  setLoading(true)

  await AsyncStorage.setItem('token', token, (error) => {
    if (token == 'wrong') {
      setIsLoggedIn(false)
      setLoading(false)
      ToastAndroid.show(
        'error',
        ToastAndroid.SHORT
      )
    } else if (!error) {
      setIsLoggedIn(true)
      setLoading(false)
    }
  })
  return token
}

It seems like you don't even modify token. It doesn't make sense to return it. You can use responseJson.token instead:

const SignIn = () => {
  screensplash()
  fetch('http://api.megamouj.ir/api/v1/logincheck/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: username,
      password: password
    })
  })
    .then((response) => response.json())
    .then((responseJson) => login(responseJson.token))
    .then(() => {
      setToken(responseJson.token)

      getMoviesFromApiAsync()
    })
}

and

const login = async (token) => {
  setLoading(true)

  await AsyncStorage.setItem('token', token, (error) => {
    if (token == 'wrong') {
      setIsLoggedIn(false)
      setLoading(false)
      ToastAndroid.show(
        'error',
        ToastAndroid.SHORT
      )
    } else if (!error) {
      setIsLoggedIn(true)
      setLoading(false)
    }
  })
}

Upvotes: 3

Related Questions