I was making a React Movie Website in which you can search for movies and see all details about them.
And there is a default search: pushpa.
But I am stuck in one place.
The default search value is not there in the search bar but the query
state is working fine.
When I change the default value of the query state is working fine but the setQuery
is giving an error.
context.js code:
import React, { useEffect, createContext, useState } from "react";
const API_URL = `http://www.omdbapi.com/?apikey=APIKEY`;
const AppContext = createContext();
const AppProvider = ({ children }) => {
const [isLoading, setIsLoading] = useState(true);
const [movie, setMovie] = useState([]);
const [isError, setIsError] = useState({ show: false, msg: "" });
const [query, setQuery] = useState("pushpa");
const getMovies = async (url) => {
try {
const res = await fetch(url);
const data = await res.json();
console.log(data);
if (data.Response === "True") {
setIsLoading(false);
setMovie(data.Search);
} else {
setIsError({
show: true,
msg: data.error,
});
}
} catch (error) {
console.log(`An Error Occurred: ${error.message}`);
}
};
useEffect(() => {
getMovies(`${API_URL}&s=${query}`);
}, []);
return (
<AppContext.Provider value={{isLoading, isError, movie}}>
{children}
</AppContext.Provider>
);
};
const useGlobalContext = () => {
return React.useContext(AppContext);
};
export { AppContext, AppProvider, useGlobalContext };
Search.js code:
import React from 'react';
import { AppContext, useGlobalContext } from './context';
const Search = () => {
const { query, setQuery, isError } = useGlobalContext(AppContext);
return (
<>
<section id="search-section">
<h2>Search Your Favourite Movie</h2>
<form action="#" onSubmit={(e) => {e.preventDefault()}}>
<input type="text"
placeholder="Search Here"
value={query} onChange={(e) => setQuery(e.target.value)} />
</form>
<div className="card-error">
<p>{isError.show && isError.msg}</p>
</div>
</section>
</>
)
}
export default Search;
When I run my website and write something in the search bar, it shows an error:
Search.jsx:13 Uncaught TypeError: setQuery is not a function
at onChange (Search.jsx:13:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
at executeDispatch (react-dom.development.js:9041:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
at processDispatchQueue (react-dom.development.js:9086:1)
at dispatchEventsForPlugins (react-dom.development.js:9097:1)
at react-dom.development.js:9288:1
CodePudding user response:
You have to pass query
and setQuery
in AppContext.Provider
.
Your AppContext.Provider
component will look like this:
<AppContext.Provider value={{isLoading, isError, movie, query, setQuery}}>
{children}
</AppContext.Provider>