0
votes

I am building an app where the user connects to a server by entering the URL when logging in.

Each server provides an API and I can't hard-code the value for the BaseURL when creating the Axios client instance. I somehow need to globally store the URL and set it based on the user input in the login form.

So I would like to know what is a proper way to do this. I am really not sure what is the best approach to dynamically store a value that I can access when creating the API connection. Any ideas and best practice suggestions are welcome.

Here is the code for creating the API connection: client.js

import { create } from 'apisauce';

const api = create({
    baseURL: "BASE_URL_FROM_USER_INPUT" + "server/odata/"
});

export default api;

This is how I use the API: users.js

import api from './client';

const getUsers = () => api.get("/users");

export default {
    getUsers
}

This is how I will get my data:

import React, { useState, useEffect } from "react";
import usersApi from '../api/users';

const TestScreenAuthenticated = ({navigation}) => {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        loadUsers();
    });

    const loadUsers = async () => {
        const response = await usersApi.getUsers();
        setUsers(response);
    }

    ...
};

export default TestScreenAuthenticated;

1

1 Answers

0
votes

you can use the localStoreto store the baseUrl.

//save the value
localStore.setItem('baseUrl', value)

//read the value
localStore.getItem('baseUrl')