Skip to content

How to create selectors in order to listen on multiple changes in context's state? #151

@saeidalidadi

Description

@saeidalidadi

First of all, I should say thank you for your useful module. today I created a context's state and I tried to use a selector function that gets props names and returns a new state but it can't prevent unnecessary component renders. So is there any way to create such selector functions?

const init = { name: 'John', date: null }

const withReducerState = () => {
   const [state, dispatch] = useReducer(reducer, init)
   return {state, dispatch}
}

const [Provider, useContext, useName, useDate, useSelector] = constate(
     withReducerState,
     value => ({ state: value.state, dispatch: value.dispatch }),
     value => value.state.name,
     value => value.state.date,
     // Create a selector function that get an array of state props --- ['name', 'date']
     value => {
         return (selectors) => {
             console.log("$$$$$$$$$$$$$$$ selectors $$$$$$$$$$$", selectors)
             let state = {}
             for(let item of selectors) {
                state[item] = value.state[item]
             }
             console.log("$$$$$$$$$$$$$$$ selected state $$$$$$$$$$$", state)
             return state;
         }
     }
)

// In my Component I want to use the selector hook.
const MyComponent = () => {
    const {name, date} = useSelector()(['name', 'date'])

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions