0
const updateSearchTopStoriesState = (hits, page) => (prevState) => {
const { searchKey, results } = prevState

Can anyone explain to me what does the above do? why is there 2 arrow functions?

This is the whole code

const updateSearchTopStoriesState = (hits, page) => (prevState) => {
const { searchKey, results } = prevState;
const oldHits = results && results[searchKey]
? results[searchKey].hits
: [];
const updatedHits = [
...oldHits,
...hits
];
return {
results: {
...results,
[searchKey]: { hits: updatedHits, page }
},
isLoading: false
};
};
class App extends Component {
...
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
user56979
  • 59
  • 1
  • 8

2 Answers2

1

Two arrow functions in a row is known as a thunk.

Simply it can be easier to understand in this format:

function updateSearchTopStoriesState = (hits, page) {
   function updateState (prevState) {
    ...code
   }
   return updateState;
}
Daniel Duong
  • 1,084
  • 4
  • 11
0

Arrows in arrow function means implicit return. So if you see two arrows following each other, that means first function returns a function. And it's not a React thing, it's a ES2016 thing. Above answer would be correct if it was like this:

function updateSearchTopStoriesState = (hits, page) {
   return function updateState(prevState) {
    ...code
   }
//Anything you put here would be disregarded since it is after the return statement.
}

See this as a basic example:

const add = num1 => num2 => num3 => num1+num2+num3;

console.log(add(3)(4)(5));
zimmerbimmer
  • 908
  • 7
  • 24