Retrieving and storing UI configurations in a React and Redux application

Gimhan Wijayawardana
2 min readJan 24, 2023

--

Hi all, Recently, I had the opportunity to work on a project where we needed to retrieve UI configurations from an endpoint and store them in our React and Redux application. This proved to be a bit challenging, but with the help of some best practices and the right tools, we were able to achieve this successfully.

In this blog post, we’ll be discussing how to call an endpoint that returns JSON data, including the UI configurations of a React application, during login and set the response to the Redux store. We’ll also go over how to access these values after they have been set in the store.

First, let’s take a look at the endpoint we’ll be calling. The endpoint should return a JSON object containing the UI configurations for our application. For example, it might look something like this:

{
"config": {
"buttonColor": "blue",
"fontSize": "16px"
}
}

To call this endpoint and set the response to the Redux store, we’ll need to create a new action in our application. This action should dispatch a request to the endpoint and then update the store with the received data. Here’s an example of what that action might look like:

import axios from 'axios';

export const fetchUIConfig = () => {
return (dispatch) => {
dispatch({ type: 'FETCHING_UI_CONFIG' });
axios
.get('/api/ui-config')
.then((response) => {
dispatch({
type: 'FETCHED_UI_CONFIG',
payload: response.data,
});
})
.catch((error) => {
dispatch({ type: 'FETCH_UI_CONFIG_ERROR', payload: error });
});
};
};

Next, we need to make sure that this action is being called during login. We can do this by adding a call to the fetchUIConfig function in our login action. Here's an example of how that might look:

import { fetchUIConfig } from './ui-config-actions';

export const login = (username, password) => {
return (dispatch) => {
// Perform login logic here
// ...
dispatch(fetchUIConfig());
};
};

With the above code, now our UI configuration will be fetched and stored in the Redux store after login. To access the values stored in the store, we can use the useSelector hook from the react-redux library. For example, to access the buttonColor value from the store, we can do the following:

import { useSelector } from 'react-redux';

function MyComponent() {
const config = useSelector((state) => state.uiConfig.config);
const buttonColor = config.buttonColor;
// Use the buttonColor value in your component
}

That’s it! With these steps, we’ve successfully called an endpoint to retrieve UI config data during login, set the response to the Redux store, and accessed the values from the store in our component.

I hope this guide was helpful and easy to follow. If you have any questions or feedback, please feel free to reach out. Happy coding!

--

--