1

In my application i have many part of the state that is significative only when the user is logged in.

When the user is logged in and navigate directly to a page, router display the page but have to make async call, so a piece of the state is not yet populated.

Now, suppose i have to show a button on navigation bar that have to take a part of the state, but this state is not populated since the async call finis.

More pratically, i have this selector:

export const getSelectedCustomer = state => state.systems.selectedCustomer;

With this, there are no problem, because selectedCustomer is part of the initialState reducer

The problem is in this selector:

export const getSelectedCustomerName = state => {
    return state.systems.entities[getSelectedCustomer(state)].customer;
}

The part of the state entities in initialState is an empty array and will be populated on async call.

So, when the application start and i map (with connect - mapStateToProps) the selector getSelectedCustomerName i get the error because entities is empty and sure, customer field do not exist yet

A simple solution if to take in place some if-else, but i will have to do this in "every" part of the application.

I'm asking if there is a better solution to avoid this...

0

1 Answer 1

2
const NullCustomerEntities = {
    customer: "Anonymous"
}

export const getSelectedCustomer = state => state.systems.selectedCustomer;

export const getCustomerEntities = state => {
    return state.systems.entities[getSelectedCustomer(state)] || NullCustomerEntities;
}

export const getSelectedCustomerName = state => {
    return getCustomerEntities(state).customer;
}

This is a classic example of a Null Object pattern (hope you don't mind the code being in Ruby).

Sign up to request clarification or add additional context in comments.

1 Comment

Stumbled on this. Enjoyed the JavaScript/Ruby juxtaposition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.