I'm currently working through a tutorial on React and I'm having trouble understanding the syntax of these arrow functions, particularly when there are multiple parameters. I'm coming from Python and am still learning JS so please keep that in mind.
With the following function:
// ADD LEAD
export const addLead = (lead) => (dispatch, getState) => {
axios
.post('/api/leads/', lead, tokenConfig(getState))
.then(........)
}
Why do we need multiple arrows? Why is lead
in one set of parenthesis and dispatch
and getState
in another set? Coming from Python this syntax is incredibly confusing and non-intuitive.
Thanks for any help!
addLead
is a function that returns a function. Here's the same thing using function body syntax instead of concise body syntax, which may be clearer:
export const addLead = (lead) => {
return (dispatch, getState) => {
axios
.post('/api/leads/', lead, tokenConfig(getState))
.then(........)
};
}
So you'd call addLead
to get a function with lead
bound to it:
const f = addLead("some lead");
...and then call that with dispatch
and state
as appropriate:
f("dispatch", "state");
Side note: It's a bit odd (without more context) that the function addLead
returns doesn't return the result of calling axios
. I would have expected it to be:
export const addLead = (lead) => (dispatch, getState) =>
axios
.post('/api/leads/', lead, tokenConfig(getState))
.then(........);
which is:
export const addLead = (lead) => {
return (dispatch, getState) => {
return axios
.post('/api/leads/', lead, tokenConfig(getState))
.then(........);
};
};