Mobx React Reactivity with Hooks and Observer - mobx

I've updated the app to use Mobx-react 6 along with Mobx state tree.
I'm not able to get the latest value inside the component when I use custom store hooks.
import { observer, MobXProviderContext, useObserver } from 'mobx-react';
function useStores() {
return useContext(MobXProviderContext);
}
function useJob() {
const { jobStore } = useStores();
return useObserver(() => jobStore);
}
//USAGE
function ChildDocs(props) {
const jobStore = useJob();
const { validChildDocuments, setCurrentChildDoc, currentChildDoc, noneDocuments } = jobStore;
//This won't update although the value in the store is null after re-mount. This shows the old value
console.log('verificationDataStore=', currentChildDoc.verificationDataStore);
}
export default observer(ChildDocs);

Related

React native changing instance prop not rerender component

I have an entity class called order
const order = new Order({status: 'available'});
export default class Order {
constructor({status}) {
this.status = status;
}
isCanceled() {
return this.status === CANCELED;
}
}
when passing order to a component throw mapStateToProps
when the status changes. mapStateToProps will be called again with the new status but the component will not be rendered with the new data
but if I passed the order as a standard object it will re-render with the new data
This code is not working
const mapStateToProps = (state, props) => {
const order = new Order({status: 'available'});
return {
order,
};
};
This code works
const mapStateToProps = (state, props) => {
const order = new Order({status: 'available'});
return {
order: {...order},
};
};
I need the first code to work as I use some functions from the object inside the component like isCanceled()
Hello all I knew what was the issue
the problem was in my reducer as I was changing in the state directly so the method wasn't pure function. So, react didn't recognize the change in props
this link has an example
React Native components not re-render if props changed
can you try this, while keeping the {...order} (2nd method you're using)
export default class Order {
constructor({status}) {
this.status = status;
this.isCanceled = this.isCanceled; //add this line
}
isCanceled() {
return this.status === CANCELED;
}
}

why chatMsgStore.addChatMsg(bdmsg) does not effect the store?

store.js
import {useLocalObservable} from "mobx-react-lite";
function chatStore() {
return {
chatmsg: [],
setChatMsg(arr) {
this.chatmsg = arr
},
addChatMsg(msg) {
this.chatmsg.push(msg)
}
}
}
export const useChatStore = () => useLocalObservable(chatStore)
app.js
const App = () => {
const chatMsgStore = useChatStore()
const AppFunctions = {chatMsgStore}
useEffect(() => {
socket.on(activechat.chatid, (bdmsg) => {
chatMsgStore.addChatMsg(bdmsg)
})
return () => {
socket.off(activechat.chatid)
}
}, [activechat, chatMsgStore.chatmsg])
return (
<>
<AppContext.Provider value={AppFunctions}>
.....................
</AppContext.Provider>
</>
)
}
export default App;
fetch.js
async function getChatMessages(url, body, userStore, chatMsgStore) {
........
chatMsgStore.setChatMsg(firstResData)
........
on app load i add a socket listener which deps are activechat and chatMsgStore.
this listener is dynamic and must be changed when deps change.
the only purpose of this listener is to add a msg to the store and re-render the observer component
deps :
activechat - non store state
chatMsgStore.chatmsg - store state
why chatMsgStore.addChatMsg(bdmsg) does not effect the store? so deeply nested components inside App.js is not re-rendering.
otherwise i have a function getChatMessages which i import from custom hook deep inside App.js which sets the messages. this func is not a child of App.js and it is not wrapped with observer chatMsgStore.setChatMsg(firstResData) works! i can set the message so the observer component will re-render
how to make this code in useeffect above work?
Your App component is not wrapped with observer HOC so it won't react to observable values changes.
Wrap it like that:
const App = observer(() => {
// ...
})
or when exporting:
export default observer(App)
More info in the docs
you should use autorun from mobx in order to set correctly the reactivity in useEffect, here is a link to the doc that explains why and how use it.
But I think that you should not put chatMsgStore.chatmsg inside the deps array because you're not using it inside the useEffect.
If you can provide a working example maybe we can help you further.

Returning Apollo useQuery result from inside a function in Vue 3 composition api

I'm having some issues finding a clean way of returning results from inside a method to my template using Apollo v4 and Vue 3 composition API.
Here's my component:
export default {
components: {
AssetCreationForm,
MainLayout,
HeaderLinks,
LoadingButton,
DialogModal
},
setup() {
const showNewAssetModal = ref(false);
const onSubmitAsset = (asset) => {
// how do I access result outside the handler function
const { result } = useQuery(gql`
query getAssets {
assets {
id
name
symbol
slug
logo
}
}
`)
};
}
return {
showNewAssetModal,
onSubmitAsset,
}
},
}
The onSubmitAsset is called when user clicks on a button on the page.
How do I return useQuery result from the setup function to be able to access it in the template? (I don't want to copy the value)
You can move the useQuery() outside of the submit method, as shown in the docs. And if you'd like to defer the query fetching until the submit method is called, you can disable the auto-start by passing enabled:false as an option (3rd argument of useQuery):
export default {
setup() {
const fetchEnabled = ref(false)
const { result } = useQuery(gql`...`, null, { enabled: fetchEnabled })
const onSubmitAsset = (asset) => {
fetchEnabled.value = true
}
return { result, onSubmitAsset }
}
}
demo

Vue 3 composition API with updating refs

I am passing a ref value to a composable function, updateableSetting. This has an initial value, settingA, but can be updated by the user. When updated, us it possible to have useFeature run again and return an updated feature value?
export default defineComponent({
setup() {
const updateableSetting = ref('settingA')
const { feature } = useFeature(updateableSetting.value)
}
})
Sure. Use a computed property
import { ref, defineComponent, computed} from 'vue'
const useFeature = (initialRef) => {
const feature = computed(() => initialRef.value + ' - I am always up to date!')
return {
feature
}
}
export default defineComponent({
setup() {
const updateableSetting = ref('settingA')
//make sure you don't pass .value here - pass the whole ref object instead
const { feature } = useFeature(updateableSetting)
return { feature }
}
})
If you mean "run a function everytime updatedValue changes", you can use
watch(
[updatedValue],
() => {console.log('updatedValue changed! doing some calculations...')}
)
I had same problem when using composables in nuxt 3.
In nuxt 3 new reactive state is available called useState. try useState instead of ref.
for more information see nuxt 3 document: useState nuxt3

How to access Vuex map helpers with Composition API

I am using Composition API in Vue2. Can you tell me how to access mapState with composition API? I want to watch for state changes as well. Hence I would have to use it within setup function as well (not only in return). Thanks
The Vuex map helpers aren't supported (yet?) in the Vue 2 or Vue 3 composition API, and this proposal for them has been stalled for a while.
You'll have to manually create a computed like in the docs:
const item = computed(() => store.state.item);
A more complete example:
import { computed } from 'vue';
import { useStore } from 'vuex';
export default {
setup() {
const store = useStore();
const item = computed(() => store.state.item);
return {
item
};
}
}
For me the trick was using the vuex-composition-helper npm package.
https://www.npmjs.com/package/vuex-composition-helpers
import { useState, useActions } from 'vuex-composition-helpers';
export default {
props: {
articleId: String
},
setup(props) {
const { fetch } = useActions(['fetch']);
const { article, comments } = useState(['article', 'comments']);
fetch(props.articleId); // dispatch the "fetch" action
return {
// both are computed compositions for to the store
article,
comments
}
}
}