facebookarchive / redux-react-hook

React Hook for accessing state and dispatch from a Redux store
MIT License
2.16k stars 103 forks source link

question about mutability of returns from useMappedState #44

Closed gcloeval closed 5 years ago

gcloeval commented 5 years ago

Hi thank you very much for this library, its working really nicelly for us.

I have a small question just to confirm if this is expected behavior For the basic scenario, i.e:

...

const mapState = useCallback(() => {
    return {
      mappedQuery: getQueryByName(requestId, queryName, store.getState())
    }
  }, [])

  let { mappedQuery } = useMappedState(mapState)

return mappedQuery 

...

Now component thats using that hook can updated the returned query directly, i.e. mappedQuery.fieldName = "XXXX" If I display the store state immediatelly after that, I see that the change is reflected directly there.

Is that the expected behavior, and if so, what is the recommended way to ensure all the updates are actually going through dispatch? Should we return a deep copy of the object from the custom hook?

gcloeval commented 5 years ago

I have updated the codesandbox here:

https://codesandbox.io/s/vqnwv5xk97

For some reason on that sandbox it fails if you try to do:

const store = useContext(StoreContext)

So instead I just propagated the store to the list and I display the contents of the store there. As you can see, customer.firstName property is updated directly in the store.

Can you provide some advice on how to prevent this? I dont remember this being the behavior with old redux mapStateToProps - somehow I think they were already readonly, but I may be mistakend. Thanks,Cheers

ianobermiller commented 5 years ago

Neither redux-react-hook nor react-redux ensures immutability of your data. You can use Object.freeze in your reducer if you want that.

Also, that fiddle is using an old version (v2.0) of redux-react-hook, which is why StoreContext is not there. I'll get that fixed up.