Home > front end >  React useState hook - set value
React useState hook - set value

Time:03-28

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)
            })
    }

CodePudding user response:

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.

  • Related