Reputation: 17773
I have this piece of code:
const App = () => {
const [selectedMovie, setSelectedMovie] = useState(null);
return (
<>
<AppHeader onSearchClick={() => setSelectedMovie(null)} />
<AppBody selectedMovie={selectedMovie} onMovieSelect={setSelectedMovie} />
<AppFooter />
</>
);
};
Recently I'm refactoring to FP
style. To make it look nice I would like to avoid calling setSelectedMovie(null)
in onSearchClick
lambda.
What I would like to achieve is to pass a function that will ignore onSearchClick
arguments and will be called with fixed null
, something like this:
<AppHeader onSearchClick={setSelectedMovieCalledWithNullOnly} />
Is it possible, e.g. with lodash
?
Upvotes: 1
Views: 94
Reputation: 191976
You can use _.wrap()
to supply a constant value to the function:
const fn = x => console.log(x)
const alwaysNull = _.wrap(null, fn)
fn(5) // 5
alwaysNull(1243281) // null
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
If there might be other params, and you to limit the function, you can also use _.ary()
to set the arity of the function (the number of parameters the function accepts) to 0
:
const fn = (...args) => console.log(args)
const alwaysNull = _.ary(_.wrap(null, fn), 0)
fn(5) // 5
alwaysNull(1, 2) // null
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
And in your case:
const App = () => {
const [selectedMovie, setSelectedMovie] = useState(null);
const setSelectedMovieCalledWithNullOnly = _.wrap(setSelectedMovie, null);
return (
<>
<AppHeader onSearchClick={setSelectedMovieCalledWithNullOnly)} />
<AppBody selectedMovie={selectedMovie} onMovieSelect={setSelectedMovie} />
<AppFooter />
</>
);
};
Upvotes: 1