1

I'm new to Reactjs and I'm developing a simple application using React and SocketIO. I'm trying to declare a global variable and assign {data.name} value to it (code shown below).

socket.on('loginSuccess', function (data) {
if (data.type == 'teacher') {
    ReactDOM.render(
        <div><TeacherLayout userName={data.name}/></div>,
        document.getElementById('root')
    );
} else {
    ReactDOM.render(
        <div><StudentLayout userName={data.name}/></div>,
        document.getElementById('root')
    );
}
reactCookie.save('sid', data.id);
});

I want to pass the global variable to userName of the code shown below,

socket.on('sessionstart', function (data) {
    ReactDOM.render(
        <div><MainLayout userName={globalVariable}/></div>,
        document.getElementById('root')
    );
}
reactCookie.save('sid', data.id);
 });

I would really appreciate some help. Thanks.

2
  • You could technically just assign it to a new property on the global window object, but it's not the best solution in most cases. If you provide more details about what you want to accomplish it's more likely people will be able to help you find more appropriate solutions :) Commented Sep 8, 2018 at 15:20
  • I have added more information on the problem. Thanks Commented Sep 8, 2018 at 16:51

1 Answer 1

1

You can use localstorage for this.

//Set your gloabal variable from any where in your app by
localStorage.setItem("key(variable-name)","value")


//Get your gloabal variable from any where in your app by
localStorage.getItem("key(variable-name)")
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Worked like a charm!

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.