-
Hi! I guess my use case has been battle-tested. I only use functional React components, no class. The documentation is heavily "class orientated" so I did not find an answer. I have a problem rendering within a component an array of objects fetched against an external API. My question is: can I only perform a Mobx state update outside of a component? For example, If I want to reach for a page that renders an array. I can update the Mobx state before rendering, this seems to work (code "index.js"). But suppose that within a page, I may need a Mobx state update, (via a button or websockets), so I want to update the Mbox state that is used within a component. However, there is no rendering (see code for Users). My Mobx store. Proxying the Mobx state update function // myStore.js
export const myStore = observable({
users: null,
fetchMbxUsers: action( async () => {
const response = await fetchUsers();
myStore.users = response
})
}); // MbxUser.js
export default observer(({user}) => <p>{user.email}</p>) My "Users" component fetches the data from an external API to render it line by line. // MbxUsers.js
const LazyUser = lazy(()=> import("./User"))
// this component only renders if the Mobx state is run outside, so when the 2 first lines are removed
export default observer(({ store }) => {
runInAction(() => store.fetchMbxUsers())
.then(() => {
console.log("store.users") );
//<-- state is indeed updated but nothing is returned
return (
<>
{store.users &&
store.users.map((user) => (
// <- each "user' is indeed present
<>
<LazyUser key={user.email.toString()} user={user} />
</>
))
}
</>
);
}); If I update the state outside of a component before rendering, it works. // index.js
import {myStore} from "./store"
const LazyUsers = lazy(()=> import("./Users"))
runInAction(()=> myStore.fetchMbxUsers()).then(()=>
root.render(
<StrictMode>
<App>
<LazyUsers store={myStore}/>
</App>
</StrictMode>
); However, this is like navigating to a new page. How could I render a component without calling the update function outside of it? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
It seems to me that you're lacking some basics of how react works (and perhaps promises). I would suggest to get familiar with these first and introduce mobx later. |
Beta Was this translation helpful? Give feedback.
It seems to me that you're lacking some basics of how react works (and perhaps promises). I would suggest to get familiar with these first and introduce mobx later.
If you want to perform an async work (like fetching users) when a component "appears" or "updates", take a look at
https://reactjs.org/docs/hooks-effect.html