text: import { useState, useEffect } from 'react'
  //api
  import API from '../API'
  //helper
  import { isPersistedState } from '../helpers'
  
  const initialState = {
    page: 0,
    results: [],
    total_pages: 0,
    total_results: 0,
  }
  
  export const useHomeFetch = () => {
    const [searchTerm, setSearchTerm] = useState('')
    const [state, setState] = useState(initialState)
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState(false)
    const [isLoadingMore, setIsLoadingMore] = useState(false)
  
    const fetchMovies = async (page, searchTerm = '') => {
      try {
        setError(false)
        setLoading(true)
  
        const movies = await API.fetchMovies(searchTerm, page)
  
        setState((prev) => ({
          ...movies,
          results:
            page > 1 ? [...prev.results, ...movies.results] : [...movies.results],
        }))
  
        console.log('useEffect')
      } catch (error) {
        setError(true)
      }
  
      setLoading(false)
    }
  
    //initial render and search
    useEffect(() => {
      if (!searchTerm) {
        console.log('Grabbing from sessionStorage')
        const sessionState = isPersistedState('homeState')
  
        if (sessionState) {
          console.log('Saving grabbed state from session storage')
          setState(sessionState)
          return
        }
      }
  
      console.log('Grabbing from api')
      setState(initialState)
      fetchMovies(1, searchTerm)
    }, [searchTerm])
  
    //load more
    useEffect(() => {
      if (!isLoadingMore) return
      fetchMovies(state.page + 1, searchTerm)
      setIsLoadingMore(false)
    }, [isLoadingMore, searchTerm, state.page])
  
    //write to sessionStorage
    useEffect(() => {
      if (!searchTerm) {
        sessionStorage.setItem('homeState', JSON.stringify(state))
      }
    }, [searchTerm, state])
  
    return { setSearchTerm, searchTerm, state, loading, error, setIsLoadingMore }
  }
  