Closed jlil closed 4 years ago
That's just how MobX's useObserver works. You have to access the props inside useObserver for MobX to rerender your component when those props change. You are meant to do something like this:
const MyComponent = () => {
const {
login
} = myStore
useEffect(() => {
login();
}, [login]);
return useObserver(() => {
// return your component from in here, all reactions are tracked
return login.state
})
}
@jeffijoe thanks for the quick reply.
In your example, how do you get the match
to work without using login.state
?
const MyComponent = () => {
const {
login
} = myStore
useEffect(() => {
login();
}, [login]);
return useObserver(() => {
// this doesn't react
return login.match({
pending: () => 'Pending',
rejected: () => 'Error',
resolved: () => 'Success',
});
})
}
Are you using decorators or field initializers or just plain objects? Maybe try not destructuring, the task func shouldn’t change anyway unless you are doing something funky. I never had this issue.
@jeffijoe using decorators in the store, here's the full example:
// AuthStore.js
@task
login = async () => {
return await AuthService.login();
};
// Login.js
const Login = () => {
const {authStore} = useStores();
useEffect(() => {
authStore.login();
}, [authStore.login]);
return useObserver(() => {
// this doesn't react
return login.match({
pending: () => 'Logging in',
rejected: () => 'Error logging in',
resolved: () => 'Logged in',
});
})
}
I don't know if that actually works using a decorator AND a field initializer.
Try:
login = task(async () => { ... })
@jeffijoe no dice. I can spin up a codesandbox is it helps in debugging.
Yes try that.
Closing until a reproduction is available, I use Hooks myself and have no issues here.
It looks like all the task observables and helpers aren't working out of the box with the
useObserver
hook.Example:
The only way to get it working is by using the following workaround: