I need clarification and some help for a task at work. We have a dashboard that has 2 modes, Sandbox and Production. I have a toggle that switches between the modes. Shown here: Sandbox Production
I want to be able to switch views and if possible the APIs I call when I toggle each mode. Please how can I go about this? I would appreciate any help
I created the toggle bottom in the navbar like this:
import { Switch, Text } from @chakra-ui/react
const [mode, setMode] = useState(true);
function switchMode() {
setMode(!mode)
}
<Text fontSize={15} mr={2}>
{mode ? "Sandbox" : "Production"}
</Text>
<Switch onChange={switchMode} />
We have 2 APIs, one for each mode. How can I switch between the two APIs when I toggle the modes?
This is my .env file
VITE_BACKEND_SANDBOX_URL = http://localhost:8000
VITE_BACKEND_PRODUCTION_URL = http://localhost:4000
This is how I’m calling the API:
const getAllCustomers = async (rows, page, token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
},
};
const response = await axios.get(
`${import.meta.env.VITE_BACKEND_SANDBOX_URL}/api/v1/customer/paginate-customer?page=${page}&rows=${rows}`,
config
);
return response.data;
};
2
Answers
There are several ways to handle it.
First and simplest approach is to store the flag whether the current env is sandbox or production in localStorage whenever there’s an update, and before calling any API endpoint, check that value each time, update the base URL accordingly. You’d probably want an API config file that pulls data from environment variables and store them.
Psuedo-code:
Another approach is, you can create a global context that stores the flag while also keeping it in localStorage. This way, you only need to pull the localStorage data once when the app mounts for the first time and work with the context state going forward.
You can create an environment file like the following
As you can see above, we are exporting the Environment and reloadEnvironmentConfig function, which will be used to reload the environment
in your screen import both Environment and reloadEnvironmentConfig function
You can even go further and create an Api class, that manages your api request
Then in your get all customers function you do
DEMO