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

98
Visualizações
useSelector cannot make real time update once the state is changed in react

I'm implementing a search functionality by using react and redux thunk. The requirement for this search is to get fetchApi called in the thunk and update the state so we can display. The ui part is like this:

function Search({fetchDataApi}) {
  const [data, setData] = useState([])
  const [token, setToken] = useState('')
  const dataFromState = useSelector(state=>state.newData) || []
  const handleSubmit = () => {
    fetchDataApi(token) // dispatch new data inside.It get updated by checking getState()
    setData(dataFromState)
  }
  const handleOnChange =(e)=> {
      setToken(e.target.value)
  }
  return (
    <div className="App">
        <input onChange={handleOnChange}/>
     <button onClick={handleSubmit}>Search</button>
     {data.map(item=><li>{item}</li>)}
     
    </div>
  );
}

export default App;

When I first click the button I got api called and state got update too, but useSelector won't return it in real time, so only empty array set by setData. When I click the button second time, the data shows up. Is it something with the useSelector or other reason to cause this issue? This is the thunk action which I simplify:

const fetchDataApi = async(token, getState, dispatch) => {
...error handle
const response = await api(token)
dispatch(setNewData(response))
...console.log(getState()) // get updated successfully 
}

setNewData is a regular action which matches the reducer This is the setNewData:

export const setNewData= (data)= ({
 type: 'SET_NEW_DATA'
 data
})

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I think this post answer my question perfectly. redux state value changed at second click I resolve this issue by using useEffect. Thanks for the checking.

about 4 years ago · Juan Pablo Isaza Relatório

0

I think the issue is inside your handleSubmit function. You're calling setData when the 'dataFromState' may not be updated yet.

It also looks like that extra local state is unnecessary. I would map over dataFromState instead of keeping an exact copy around. See below:

function Search({fetchDataApi}) {
  const [token, setToken] = useState('')
  const dataFromState = useSelector(state=>state.newData) || []
  const handleSubmit = () => {
    fetchDataApi(token) // dispatch new data inside.It get updated by checking getState()
  }
  const handleOnChange =(e)=> {
      setToken(e.target.value)
  }
  return (
    <div className="App">
        <input onChange={handleOnChange}/>
     <button onClick={handleSubmit}>Search</button>
     {dataFromState.map(item=><li>{item}</li>)}
     
    </div>
  );
}

export default App;
about 4 years ago · Juan Pablo Isaza 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