1

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?

1
  • Perhaps pricing is getting rendered before App. Try putting a console log in the useEffect of pricing and see which one comes up first Commented Jun 9, 2020 at 13:10

1 Answer 1

1

(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]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.