skip to Main Content

I’m a beginner in react native, I’m trying to get user information from mysql database through an axios API get request.

Once logged in, I stored email address in AsyncStorage and later want to use that email address from AsyncStorage as params or parameters to get the user details.

I wrote a code which set initial state of the setState as ‘na’. Please help me how I can pass the email address from AsyncStorage as params or parameters.

Here is my code.

// to load email address
  const [SessionEmail, setSessionEmail] = useState('na');

// to load users info
  const [users, setUsers] = useState([]);
  useFocusEffect(
    React.useCallback(() => {   
      getUsername();
      getUsersInfoFromAPI();
    }, [])
  );
// to get the session username from localstorage
  const getUsername = async () => {
    try {
      const username = await AsyncStorage.getItem('Username')
      if (username !== null) {
        setSessionEmail(username);
      }
    } catch (e) {
      console.log(e);
    }
  }

 // API Calling user details
  const getUsersInfoFromAPI = async () => {
    await axios.get(`https://myapi.co.in/api/user/?email=${SessionEmail}`)
      .then(response => {
        setUser(response.data);
      })
      .catch(error => {
        console.log(error);
      });
  }

After the page is rendered, and I load page from metro, I can see the parameters have been sent to server.

2

Answers


  1. const [users, setUsers] = useState([]);
    

    here you can use like this

      const [users, setUsers] = useState();
    

    hope this will help you

    Login or Signup to reply.
  2. Update your code in this way:

    useFocusEffect(
        React.useCallback(() => {   
          getUsername();
        }, [])
      );
    

    Instead of saving your email to state, sent it to function directly but if you are using it for other reason you can still save it but call function while getting username from AsyncStorage with username parameter like below.

    // to get the session username from localstorage
      const getUsername = async () => {
        try {
          const username = await AsyncStorage.getItem('Username')
          if (username !== null) {
            getUsersInfoFromAPI(username);
          }
        } catch (e) {
          console.log(e);
        }
      }
    
    // API Calling user details
      const getUsersInfoFromAPI = async (email) => {
        await axios.get(`https://myapi.co.in/api/user/?email=${email}`)
          .then(response => {
            setUser(response.data);
          })
          .catch(error => {
            console.log(error);
          });
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search