Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
controlled-component-with-hooks2.jsx
function useSetUp({ initialSearch = "", initialResult = [] }) {
const [search, setSearch] = React.useState(initialSearch);
const [result, setResult] = React.useState(initialResult);
return {
search,
setSearch,
result,
setResult,
};
}
function SearchAndResultView({ search, setSearch, result }) {
return (
<Modal>
<SearchBox search={search} setSearch={setSearch} />
<ResultContainer result={result} />
</Modal>
);
}
SearchAndResultView.useSetup = useSetUp;
function AnyofyourComponent() {
const { search, setSearch, result } = SearchAndResultView.useSetup();
async function onSearch(e) {
const value = e.target.value;
setSearch(value);
// do some API call
const res = await fetch("https://random-api");
setResult(res.data);
}
return (
<SearchAndResultView
search={search}
setSearch={setSearch}
result={result}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment