Override the constant file values in React

Viewed 1014

constant file -> constant.js

export default {
  CITY: 'Banglore',
  STATE: 'Karnataka'
}

Show Default City Name -> address.jsx

import React from "react";
import CONSTANTS from "./constants";
import "./styles.css";

const Address = () => {
  return (
    <div className="App">
      <p> City : {`${CONSTANTS.CITY}`} </p>
      <p> State : {`${CONSTANTS.STATE}`} </p>
    </div>
  );
};
export default Address;

expected output:

city: banglore
state: karnataka

we are importing the constant values from constant.js file, now the problem is we have to make one API call which may return overriding values for the constant keys

example of API response:

{
  CITY: 'Mysuru'
}

then CITY is constant file should override with the new value which come after API response and rest other keys should keep their values same.

expected output:

city: Mysuru
state: karnataka

this the basic problem case for me, actually our application already in mid phase of development and more than 500+ constant keys are imported in 100+ components.

1. we are using redux in our application

2. we have to call API only once that should effects to all the components

what is the best way to achieve this problem, how can i override my constant files once i make the call to backend, Thank you

1 Answers

Since the question has changed, so does my answer (keeping the original one below). I'd suggest to rebuild the constants file to either return the constants or from Localstorage. However, be aware that the current components will not be rebuild using this approach. Only thing that'll trigger a rebuild is either use Redux for this or local state management.

const data = {
  CITY: 'Banglore',
  STATE: 'Karnataka'
}

const getData = () => {
  let localData = window.localStorage.getItem('const-data');

  if (!localData) {
    axios.get('url')
      .then(response => {
        localData = {...response.data};
        window.localStorage.setItem('const-data', JSON.stringify({...localData}));
      });
  }

  return localData ? localData : data;
}

export default getData();

Original answer:

This is how I'd solve it using local state. It was some time ago since I was using Redux. Though the same principle should apply instead of putting the data in local state, put it in the Redux.

I prefer the simplicity of using local state whenever there's no need to share data over multiple components.

import React, { useEffect } from "react";
import CONSTANTS from "./constants";
import "./styles.css";

const Address = () => {
  const [constants, setConstants] = useState({...CONSTANTS});
  
  useEffect(() => {
    //api call
    //setConstants({...apiData});
  }, []);
  
  return (
    <div className="App">
      <p> City : {`${constants.CITY}`} </p>
      <p> State : {`${constants.STATE}`} </p>
    </div>
  );
};
export default Address;
Related