I am trying to save a variable from the user collection to the client so that I can use it, but I don't want the client to be able to change the variable. How do I achieve this?
Currently I have this, but it keeps switching on and off cause it doesn't always get the variable from the collection while rendering:
function AdminMenu() {
const user = useTracker(() => Meteor.user());
if (user.admin) {
return (
<div>isAdmin</div>
);
} else {
return (<div/>);
}
}
I can get it to work the way I want like this, but I am afraid that the client is able to edit the variable:
let isAdmin = false;
function AdminMenu() {
const user = useTracker(() => Meteor.user());
if (user.admin) {
isAdmin = true;
}
if (isAdmin) {
return (
<div>isAdmin</div>
);
} else {
return (<div/>);
}
}
What is the best way to achieve this? Thanks in advance!
The reason for the change is that the subscription isn't ready when the component first renders, but once it is ready tracker will cause the template to rerender and show the new state. To fix this you'll need to subscribe within your use tracker hook and only render once the subscription becomes ready. Give this a try.
function AdminMenu() {
const { user, ready } = useTracker(() => ({
user: Meteor.user(),
ready: Meteor.subscribe('your-subscription-name').ready();
}));
if (ready && user.admin) {
return (
<div>isAdmin</div>
);
} else {
return (<div/>);
}
}
There is another method of dealing with this that is a bit more complex so I won't detail it here, but see my comment above and come join the Meteor Community Slack and I'm more than happy to help you further if you'd like.