1

I am using functional component and trying to achieve MVVM. I want to get updated value of redux state without using useSelector hook

Here is my code

model.js

export class Model {
    getData = () => {
        return store.getState().mReducer.jsonData
    }
    setData = (data) => {
        store.dispatch(setData(data)) // storing in redux for further use
    }
}

ViewModel.js

export class ViewModel {
    onChangeTextHandler = (text) => {
    this.model.setData(tmp)
   }
}

View.js

export const View = () => {
const vm = useMemo(() => new ENReceivingViewModel(), [])
const model = useMemo(() => new ENREceivingModel(), []);
//IF I use this line then rerender happens otherwise nothing happens
//const { selectedOption, jsonData } = useSelector(state => state.ReceivingReducer)
return (
    <TextInput value = {model.getData()[0]}
    onChangeText={vm.onChangeTextHandler} />
)}
Uzef Shaikh
  • 636
  • 6
  • 11

1 Answers1

0

I don't think that would be possible to handle it in this way, the model object keeps the only value of the store that was in the initialization.

I think passing store to method of class will do what you want:

like this:

export class Model {
    getData = (store) => {
        return store.getState().mReducer.jsonData
    }
    setData = (data) => {
        store.dispatch(setData(data)) // storing in redux for further use
    }
}

and in component:

import store from "./store"
  <TextInput value = {model.getData(store)[0]}
    onChangeText={vm.onChangeTextHandler} />

or another way is to add dependency in useMemo

like this :

const model = useMemo(() => new ENREceivingModel(), [someState]);

in this way every time that someState changes, a new ENREceivingModel will be replaced the previous one

Ali Sattarzadeh
  • 3,220
  • 1
  • 6
  • 20
  • Tried passing store inside my getData as you mentioned but that also didn’t work and as you have seen my code i do not have any other state which i can use to refresh the useMemo though, I tried to force re-render my functional component and when I force it to re-render It works as expected but I don’t think that it is a good way to doing this because force rendering everytime whenever text change may cause a memory leak at some point. – Uzef Shaikh Jan 31 '23 at 08:21
  • Another possibility is to subscribe to the store and when the state of redux changes re-render the UI but it is again to re-render so is it possible to get latest value without re-rendering – Uzef Shaikh Jan 31 '23 at 08:51