简体   繁体   中英

Infinite loop of useEffect with empty dependency array

code running correctly while in fulfilled case of extraReducer isLoading's state is not used SearchForm component is not written fully, just what is needed to understand the issue

const fetchMovies = createAsyncThunk(
  'movies/fetchMovies',
  async (movieTitle) => {
    const newMovies = await searchApi.findMovie(movieTitle)
    return newMovies
  }
)

extraReducers: (builder) => {
    builder
      .addCase(fetchMovies.pending, (state, action) => {
        state.isLoading = true
      })
      .addCase(fetchMovies.fulfilled, (state, action) => {
        state.isLoading = false // running an infinite loop
        }
      })


import { fetchMovies } from '../../redux/slices.js/moviesSlice'
export function SearchForm() {
  const dispatch = useDispatch()

  // movies default value
  useEffect( () => {
    dispatch(fetchMovies('Titanic'))
  }, [])
  

  return (
    <form>
      <input></input>
      <button></button>
    </form>
  )
}

Your code is still very incomplete. I have no idea why you're using useEffect to fetch the movies. Because of the way your SearchForm component is laid out, I guess that the user searches for a movie title, submits and then the action of fetching the movies based on the title gets dispatched.

So in that scenario, using useEffect is not appropriate and you have to use a function to handle the submit.

import { useState } from "React"

const SearchForm = () => {

const [input, setInput] = useState("");

const handleSubmit = (e) => {
  e.preventDefault();
  if (!input) return;

  dispatch(fetchMovies(input));
}

  return (
    <form onSubmit={handleSubmit}>
      <input value={input} onChange={(e) => setInput(e.target.value)}></input>
      <button type="submit">Search</button>
    </form>
  )
}

it turns out cause I'm trying to render conditionally as follow:

export default function HomePage() {
  return(
    {isLoading 
    ? <Preloader />
    : <Routing />
    }
  )
}

as I guess it isn't correct to render this way

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