React Native: Can't fetch on onPress={}

Viewed 150

My app :

import { LoginFunction, RegisterFunction } from './authentication/auth'

export default function LoginPage(props) {
  
  const navigateToRegister = () => {
    props.navigation.navigate("Register")
  }

  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  return (
    <View style={styles.container}>

      <View style={styles.input}>
        <Text style={styles.label}>Username</Text>
        <TextInput style={styles.textinput} placeholder='...' onChangeText={(text) => setUsername(text)}/>
      </View>

      <View style={styles.input}>
        <Text style={styles.label}>Password</Text>
        <TextInput style={styles.textinput} placeholder='...' onChangeText={(pw) => setPassword(pw)}/>
      </View>
      
      <View style={styles.login}>

        // HERE IS I'M TRYING TO RUN FUNCTION
        <TouchableOpacity style={styles.loginbtn} onPress={() => {
          LoginFunction(username, password)
        }}>
        // ----------------------------------

          <Text style={styles.logintext}>Login</Text>
        </TouchableOpacity>
      </View>

      <TouchableOpacity style={styles.btn} onPress={() => navigateToRegister()}>
        <Text style={styles.text}>
          Register Instead
        </Text>
      </TouchableOpacity>

    </View>
  )
}

The function in where I imported from :

import React, { useState, useEffect } from 'react';
export function LoginFunction(username, password) {
  const [data, setData] = useState([])

  fetch('https://some**app**.herokuapp.com/api/users/', {
      method: "GET"
  })
  .then((resp) => resp.json())
  .then((resp) => {
    setData(resp)
  })
  .catch((err) => console.log("ERR: " + err))

  console.log(data)

  alert(username + " " + password)
}

I'm trying to make my own authentication system with using rest api. I tried to fetch data from api and make provide user login. But I'm getting an error with this code.

Error : Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

I dealed with this error before but I cannot now. What should I do? What is the wrong?

1 Answers

You should move the const [data, setData] = useState([]) to LoginPage component instead. The LoginFunction function accepts 3 parameters: (username, password, setData) You then can use data in the LoginPage.

Related