T
TanStack16mo ago
correct-apricot

Can I use a selector for the `store.subscribe` method?

In my project I am building a form wizard with multiple steps. Each step should report to a progress bar as soon as it becomes valid. For this I have two approaches right now. The first one is via form.subscribe:
const Validator = ({ isValid }: ValidatorProps) => {
useEffect(() => {
if (isValid) {
console.log("form is valid");
} else {
console.log("form is invalid");
}
}, [isValid]);

return <p>{isValid ? "form is valid" : "form is invalid"}</p>;
};

// usage:
<form.Subscribe
selector={(state) => [state.canSubmit]}
children={([canSubmit]) => {
return <Validator isValid={canSubmit} />;
}}
/>
const Validator = ({ isValid }: ValidatorProps) => {
useEffect(() => {
if (isValid) {
console.log("form is valid");
} else {
console.log("form is invalid");
}
}, [isValid]);

return <p>{isValid ? "form is valid" : "form is invalid"}</p>;
};

// usage:
<form.Subscribe
selector={(state) => [state.canSubmit]}
children={([canSubmit]) => {
return <Validator isValid={canSubmit} />;
}}
/>
What I like here is that I am only notified if the canSubmit state changes and nothing else, but it seems to be a bit too complicated for what I want to achieve. My other component is working with the store.subscribe method:
const HookValidator = () => {
const formApi = useFormApi();
const store = formApi.store;
const [isValid, setIsValid] = useState(store.state.canSubmit);

store.subscribe(() => {
if (store.state.canSubmit) {
console.log("form is valid");
setIsValid(true);
} else {
console.log("form is invalid");
setIsValid(false);
}
});

return <p>{isValid ? "form is valid" : "form is invalid"}</p>;
};
const HookValidator = () => {
const formApi = useFormApi();
const store = formApi.store;
const [isValid, setIsValid] = useState(store.state.canSubmit);

store.subscribe(() => {
if (store.state.canSubmit) {
console.log("form is valid");
setIsValid(true);
} else {
console.log("form is invalid");
setIsValid(false);
}
});

return <p>{isValid ? "form is valid" : "form is invalid"}</p>;
};
This is logging on each state change and not only on the state.canSubmit property. Can I select the value I want to subscribe to with store.subscribe like I can with form.Subscribe? Thanks in advance for your help!
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?