I am learning React, and I am trying to build a test app that uses the OMDB API to fetch movie information and posters. Here is some relevant code:
const getMovieRequest = async (searchValue) => {
const url = `https://www.omdbapi.com/?s=${searchValue}&apikey=${process.env.REACT_APP_OMDB_API_KEY}`;
const response = await fetch(url);
const responseJson = await response.json();
if (responseJson.Search) {
setMovies(responseJson.Search);
}
};
useEffect(() => {
getMovieRequest(searchValue);
}, [searchValue]);
I had everything working correctly on my local machine, but I did not like my function using that long reference to the API key. I created a variable to store the key which is what others have done in tutorials I have read. So this is what I created:
const OMDB_API_KEY = process.env.REACT_APP_OMDB_API_KEY;
Next, I updated the one line of code in the function so that it references the variable:
const url = `https://www.omdbapi.com/?s=${searchValue}&apikey=${OMDB_API_KEY}`;
Here is the updated code snippet with the change in place:
const OMDB_API_KEY = process.env.REACT_APP_OMDB_API_KEY;
const getMovieRequest = async (searchValue) => {
const url = `https://www.omdbapi.com/?s=${searchValue}&apikey=${OMDB_API_KEY}`;
const response = await fetch(url);
const responseJson = await response.json();
if (responseJson.Search) {
setMovies(responseJson.Search);
}
};
useEffect(() => {
getMovieRequest(searchValue);
}, [searchValue]);
Now is when it gets weird. ESLint started freaking out with this error from useEffect:
React Hook useEffect has a missing dependency: 'getMovieRequest'. Either include it or remove the dependency array.eslintreact-hooks/exhaustive-deps
I updated the dependency per ESLint's "quick fix" suggestion which changed the useEffect to look like this:
useEffect(() => {
getMovieRequest(searchValue);
}, [getMovieRequest, searchValue]);
Problem solved, right? Nope, wrong, now I get another error coming from the getMovieRequest function:
The 'getMovieRequest' function makes the dependencies of useEffect Hook (at line 32) change on every render. Move it inside the useEffect callback. Alternatively, wrap the definition of 'getMovieRequest' in its own useCallback() Hook.eslintreact-hooks/exhaustive-deps
I tried various things that I thought were what they wanted me to do. I've Googled the issue and couldn't really find the same situation I'm facing, although others have encountered the error. I've wasted a whole day fooling with this. I'm sure it's something easy or quick but I'm still learning how this React stuff works. Any help is appreciated!
Aucun commentaire:
Enregistrer un commentaire