I am changing the state in reducer. On debug I checked that the state was really changed. But the component is not updating.
Component:
function Cliente(props) { const dispatch = useDispatch() const cliente = useSelector(({ erpCliente }) => erpCliente.cliente) const { form, handleChange, setForm } = useForm(null) ... function searchCepChangeFields() { //This call the action and change the store on reducer dispatch(Actions.searchCep(form.Cep)) .then(() => { // This function is only taking values from the old state. // The useSelector hook is not updating with store setForm(form => _.setIn({...form}, 'Endereco', cliente.data.Endereco)) setForm(form => _.setIn({...form}, 'Uf', cliente.data.Uf)) setForm(form => _.setIn({...form}, 'Cidade', cliente.data.Cidade)) setForm(form => _.setIn({...form}, 'Bairro', cliente.data.Bairro)) }) }
Reducer:
case Actions.SEARCH_CEP: { return { ...state, data: { ...state.data, Endereco: action.payload.logradouro, Bairro: action.payload.bairro, UF: action.payload.uf, Cidade: action.payload.cidade } }; }
The way you have it written, the state won't update unless you explicitly update it using setState() (most likely in the componentWillReceiveProps() method). When you use mapStateToProps() with the Redux connect() HOC, you are mapping your Redux state to your component through its props, so in your case this. props.
Just connect the redux state with the component's state by using useSelector hooks, so the component will automatically re-rendered when the redux state changes.
React-redux component does not rerender on store state change.
The only way to update a state inside a store is to dispatch an action and define a reducer function to perform tasks based on the given actions. Once dispatched, the action goes inside the reducer functions which performs the tasks and return the updated state to the store. This is what Redux is all about.
NOTE: you better start using redux-toolkit to prevent references in you code its a better and almost a must way for using redux
the problem your facing is very common when handling with objects, the props do not change because you're changing an object property but the object itself does not change from the react side.
even when you're giving it a whole new object react doesn't see the property object change because the reference stays the same.
you need to create a new reference like this:
Object.assign(state.data,data); return { ...state, data: { ...state.data, Endereco: action.payload.logradouro, Bairro: action.payload.bairro, UF: action.payload.uf, Cidade: action.payload.cidade } }
to add more you can learn about the Immer library that solves this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With