Kex
Kex

Reputation: 8579

Global variable in React using import not working

I read somewhere that you can use a singleton style object, set it's value and then import it elsewhere and the value will remain. For example:

storage-util.js

const storage = {};
export default storage;

App.js

function App() {
  useEffect(() => {
    storage.token = "1234";
    console.log('set token');
  });
  return (
    <div>
      <NavbarDefault />
      <MainSwitch />
    </div>
  );

Pricing.js

const Pricing = () => {

    useEffect(() => {
        console.log(storage.token);
    });
    return (
        <h1 className="heading-text font-weight-bold text-center">
            Pricing
        </h1>
    );
};

However I am getting undefined when trying to access storage.token in Pricing.js, what am I doing wrong here?

Upvotes: 1

Views: 164

Answers (1)

HaveSpacesuit
HaveSpacesuit

Reputation: 3994

(I'm assuming you're importing storage into App.js and Pricing.js.)

When the Pricing component first mounts, storage is still undefined. The normal way to deal with that would be to introduce a dependency array to watch in your useEffect hook:

useEffect(() => {
  console.log(storage.token);
}, [storage.token]);

However, since storage isn't state, React won't be able to re-run the useEffect when storage changes. You'd be best off setting up storage as a state that you can import.

// storage-util.js
export const [storage, setStorage] = useState()

// App.js
setStorage( {token: '1234'} )

// Pricing.js
useEffect(() => {
  console.log(storage.token);
}, [storage.token]);

Upvotes: 1

Related Questions