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

111
Visualizações
React useState hook - set value

I'm new to the whole React and React hooks staff, I'm trying to reset the value in useState to default if new filters are selected.

const [apartments, setApartments] = React.useState([])
const [page, setPage] = React.useState(1)
const fetchData = (onInit = true, loadMore = true) => {
        let setQuery = ''
        if (!loadMore) {
            setApartments([]) // <--- how to reset to empty?
            setPage(1) // <--- Not setting value to 1
        }
        if (!onInit || query()) {
            filtersWrapper.current.querySelectorAll('.select-wrapper select').forEach(item => {
                if (item.value) {
                    setQuery += `&${ item.name }=${ item.value }`
                }
            })
        }
        fetch(apiUrl + `?page=${ page }&pageSize=12${ setQuery }`)
            .then(res => res.json())
            .then(data => {
                setApartments([...apartments, ...data.apartments] || [])
                setHasNextPage(data.hasNextPage)
                setPage(prev => prev + 1)
            })
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Identify the page to pass to fetch from the loadMore argument, not from the state value. Similarly, identify from the argument what to pass to setApartments. This way, all the state gets updated at once, inside the fetch.

const fetchData = (onInit = true, loadMore = true) => {
    let setQuery = ''
    if (!onInit || query()) {
        filtersWrapper.current.querySelectorAll('.select-wrapper select').forEach(item => {
            if (item.value) {
                setQuery += `&${item.name}=${item.value}`
            }
        })
    }
    const pageToNavigateTo = loadMore ? page : 1;
    fetch(apiUrl + `?page=${pageToNavigateTo}&pageSize=12${setQuery}`)
        .then(res => res.json())
        .then(data => {
            const initialApartments = loadMore ? apartments : [];
            setApartments([...initialApartments, ...data.apartments]);
            setHasNextPage(data.hasNextPage);
            setPage(pageToNavigateTo + 1);
        })
        // .catch(handleErrors); // don't forget this
}

I'd also recommend changing the

filtersWrapper.current.querySelectorAll('.select-wrapper select').forEach

from DOM methods to setting React state instead.

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