简体   繁体   中英

Why is useState value null inside function block?

I know there is a scoping issue here. I just can't find it. Why is 'items' null in the searchItems() block?

export const useStore = () => {
   const [items, setItems] = useState(null)

   const setItemsFromApi = () => {
      //call api to get data, then
      setItems(data)
   }

   const searchItems = (query) => {
      //use the local data and filter based on query
      //'items' IS NULL IN THIS SCOPE
      items.filter(() => {})
   }

   console.log(items) // 'items' HAS UPDATED VALUE AFTER setItemsFromApi() IN THIS SCOPE

   return {setItemsFromApi, searchItems}
}

Use store like this. (NOTE: I left out the rendering of the items in the list because that part works fine. Just focusing on why the onClick doesn't use the already loaded items to filter with.)

export default function DataList(props) => {     
   const store = useStore();

   useEffect(() => {
      store.setItemsFromApi()
   }, [])
    
   const runSearch = (query) => {
      store.searchItems(query)
   }

   return <button onClick={runSearch('searchTerm')}   
 }

I even tried passing it as a callback dependency, but it's still null

const searchItems = useCallback((query) => {
    //'items' IS STILL NULL IN THIS SCOPE
    items.filter(() => {})
 }, [items])

From the code you posted,

const store = useStore() store.setItemsFromApi() ... store.searchItems(query)

the issue may be because you are doing an async operation (calling the API), but the search is not waiting for the result of the fetch call. So, when you do the

store.searchItems(query)

, the store is null and only changes its value later.

In a nutshell, the state wasn't refreshing after triggering a search because I had a "debounce" useRef function running within the component when the onChange event was fired, even though this was a local data search. I guess this interrupted the re-render event. So I moved the debounce directly to the api service call for when search requires an api call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM