I'm creating a React Movie app which enables user to search for movies and add to his favorite list. This app is going to have a live search functionality with infinite loading feature so when user enters a title name a Modal will display results and user can select titles to be added to his list.
I'm so confused about managing live search and infinite loading state and their dependency. So is this approach correct or search results should be part of live search component?
const App = () => {
const [searchResults, setSearchResults] = useState([]);
const [reqQuery, setReqQuery] = useState("");
useEffect(() => {
// Request from API and store in the searchResults
}, [reqQuery]);
useEffect(() => {
// Render Results
}, [searchResults]);
return (
<>
<SearchForm onConfirmedInput={(query) => setReqQuery(query)} />
{searchResults && <Results data={searchResults} />}
</>
);
};
const SearchForm = (props) => {
const [value, setValue] = useState("");
const handleChange = (e) => {
const val = e.target.value;
setValue(val);
// If value is valid then lift-up
props.onConfirmedInput(value);
};
return <input value={value} onChange={handleChange}></input>;
};
P.S: Mentioned code is just to elaborate the issue and is not part actual app code
The approach is sound - storing state at a higher level and having SearchForm
be a component that just uses its passed in props
. A few pointers
<Movies>
. Your <App>
should be kept for things like routing and not be concerned with implementation details of specific parts of functionality. I realise you may have been trying to keep things simple and your example uncluttered, I mentioned just in case.useEffect
will work, however it isn't best practice. You should declare functions (e.g. getSearchResults
) for API calls (and more ideally, declare them in a separate service, rather than having fetch
in the component code) and pass these into your SearchForm
rather than relying on useEffect
. When the state changes (e.g. after the API is called and results returned) the component will be re-rendered after you setSearchResults(results)
and pass them down to the <SearchForm>
For infinite scroll with lazy loading I'd highly recommend the excellent react-window
library and associated components for lzay loading and auto-resize.