Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are selectors in redux?

I am trying to follow this code in redux-saga

export const getUser = (state, login) => state.entities.users[login] export const getRepo = (state, fullName) => state.entities.repos[fullName] 

Which is then used in the saga like this:

import { getUser } from '../reducers/selectors'  // load user unless it is cached function* loadUser(login, requiredFields) {   const user = yield select(getUser, login)   if (!user || requiredFields.some(key => !user.hasOwnProperty(key))) {     yield call(fetchUser, login)   } } 

This getUser reducer (is it even a reducer) looks very different from what I would normally expect a reducer to look like.

Can anyone explain what a selector is and how getUser is a reducer and how it fits in with redux-saga?

like image 894
dagda1 Avatar asked Jul 30 '16 12:07

dagda1


People also ask

What is selector and reducer?

It's generally suggested that selectors are defined alongside reducers and exported, and then reused elsewhere (such as in mapStateToProps functions, in async action creators, or sagas) to colocate all the code that knows about the actual shape of the state tree in the reducer files.

Why do we use selectors?

A selector is one of the properties of the object that we use along with the component configuration. A selector is used to identify each component uniquely into the component tree, and it also defines how the current component is represented in the HTML DOM.

Why we use selector in React JS?

The selector may return any value as a result, not just an object. The return value of the selector will be used as the return value of the useSelector() hook. When an action is dispatched, useSelector() will do a reference comparison of the previous selector result value and the current result value.


1 Answers

getUser is not a reducer, it is indeed a selector, that is, a function that knows how to extract a specific piece of data from the store.

Selectors provide an additional layer such that if you altered your store structure and all of a sudden your users were no longer at state.entities.users but instead at state.users.objects.entities (or whatever) then you only need to update the getUser selector and not every place in your app where you were making a reference to the old location.

That makes them particularly handy when it comes to refactoring your Redux store.

like image 133
horyd Avatar answered Sep 17 '22 21:09

horyd