Redux How to get updated state value without using useSelector
Asked Answered
C

1

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} />
)}
Convolution answered 30/1, 2023 at 12:43 Comment(2)
maybe use model.getData()[0] instead of model.data[0] ?Measured
I am using getData() only it was just a typeo error but getData() is not a proper solutionConvolution
E
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

Erk answered 31/1, 2023 at 7:18 Comment(2)
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.Convolution
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-renderingConvolution

© 2022 - 2024 — McMap. All rights reserved.