Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

2.1K
Visualizações
useSelector not updating when store has changed in Reducer. ReactJS Redux

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                    
                }
            };
        }  
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

It's not necessary to

Object.assign(state.data, data);

always when changing data of arrays or objects

return(
  object: {...state.object, a: 1, b: 2},
  array: [...state.array, 1, 2, 3]
)

this 3 dots (...) ensure that you create a new object. On redux you have to always create a new object, not just update the state. This way redux won't verify that your data has changed.

When having nesting objects or arrays, is the same thing

Just have attention to:

initialState = {
 object: {
     ...object,
     anotherObject:{
        ...anotherObject,
        a: 1,
        b: 2
      }
   }
}
over 4 years ago · Santiago Trujillo Relatório

0

Somehow, the Object.assgin is not recognize Update with ES6 syntax.

updatedConnectors = state.connectors

This will create a reference to the current state. In ES6, that introduce the ... to make new reference.

updatedConnectors = { ...state.connectors }
.....
return  {
    ...state,
    connectors: updatedConnectors
};

use this to extract and copy new reference. That will trigger state change too

Update Sep/27/20 I've wrote some utils function to handle this, Let try this

//Utils
export const getStateSection = ({ state, sectionName }) => {

  const updatedState = { ...state }
  const updatedSection = updatedState[sectionName]
  return updatedSection
}

export const mergeUpdatedSection = ({ state, sectionName, updatedValue }) => {
  const updatedState = { ...state }
  updatedState[sectionName] = updatedValue
  return updatedState
}

Then In any reducer, It should use like this:

//reducer
const initState = {
  scheduleDetail: null,
  timeSlots: null,
  planDetail: {
    timeSlots: [],
    modifedTimeSlots: [],
    id: 0
  }

}
.....  
const handlePickTimeSlot = (state, action) => {
  let planDetail = getStateSection({ state, sectionName: 'planDetail' })
  // do stuff update section
  return mergeUpdatedSection({ state, sectionName: 'planDetail', updatedValue: planDetail })
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda