React Native Redux Using state props and selectors together

451 Views Asked by At

In my react-native redux app, in my mapStateToProps function, I need to combine some elements from state and some selectors created using reselect.

Basically, I have two things:

const mapStateToProps = (state) => ({
    storedUserName: state.user.name,
    isUserLoggedIn: state.user.isLoggedIn,
})

const mapStateToProps = createStructuredSelector({
  email: emailSelector,
  userData: userDataSelector
});

I need a way to combine these two so that I have all 4 props with only one mapStateToProps function. I just don't know how to do this. Please help.

2

There are 2 best solutions below

0
On

Try this code

import { createSelector } from 'reselect'

const emailSel = state => state.user.email
const userDataSel = state => state.user

const emailSelector = createSelector(
  emailSel,
  email => email // you can make calculations on input and return value
) 

const userDataSelector = createSelector(
  userDataSel,
  userData => userData // you can make calculations on input and return value
) 

const mapStateToProps = (state) => ({
    storedUserName: state.user.name,
    isUserLoggedIn: state.user.isLoggedIn,
    email: emailSelector,
    userData: userDataSelector
})

Selectors : Selectors are functions that take Redux state as an argument and return some data

reselect : You will use the reselect library when you compute derived data/make calculations/apply filters on data selected by selector. Reselect is effcient.

Note : You do not need reslsect when you have to just get data from state without any calculations and filters

2
On

Selectors are functions that take Redux state as an argument and return some data to pass to the component, like this:

// selector
const getDataType = state => state.editor.dataType;

You can do is

import { getDataType } from '../selectors'

const mapStateToProps = (state) => ({
    storedUserName: state.user.name,
    isUserLoggedIn: state.user.isLoggedIn,
    
    dataType: getDataType(state) <-- selector -->
})