1

I want to reuse a react component and share common actions & reducers. My app dashboard has 3 Lists, where each List is fetched with different query param.

All 3 List components have the same props because all 3 of them are being re-rendered once I receive props from reducer.

Is there an dynamic way to display Lists based on query parameter? What I was thinking is to call different reducer in the action file based on the query param. Is there a better way?

Dashboard.js

 const Dashboard = () => { return( <div> <List query={QUERY1} /> <List query={QUERY2} /> <List query={QUERY3} /> </div> ) } 

List.js

class List extends Component { constructor(props) { super(props); this.state = { items: [] }; } componentWillMount() { const { query } = this.props; this.props.onLoad(query); } componentWillReceiveProps() { const { items } = this.props; this.setState({ items }); } render() { return ( <div> { this.state.items.map((item, index) => <Item data={item} key={index}/> ) } </div> ) } } function mapStateToProps(state) { const { items } = state.item; return { items } } function mapDispatchToProps(dispatch) { return { onLoad: bindActionCreators(actions.load, dispatch) } } export default connect(mapStateToProps, mapDispatchToProps)(List); 

action.js

export function load(query) { return function (dispatch) { fetch(`//api.example.com/list?type=${query}&limit=10`) .then((response) => response.json()) .then((data) => { dispatch(setItems(data)); }); }; } 

reducer.js

export default function(state = [], action) { switch (action.type) { case actionTypes.ITEMS_SET: return setItems(state, action); } return state; } function setItems(state, action) { const { items } = action; return { ...state, items }; } 
1

1 Answer 1

1

Note I am a contributor on redux-subpace

redux-subspace came around to solve this problem of having the same component displayed on the page, without crossing over the store values.

It has a feature called namespacing that will allow you to isolate your load actions and components from each other.

const Dashboard = () => { return( <div> <SubspaceProvider mapState={state => state.list1}, namespace='list1'> <List query={QUERY1} /> </SubspaceProvider> <SubspaceProvider mapState={state => state.list2}, namespace='list'> <List query={QUERY2} /> </SubspaceProvider> <SubspaceProvider mapState={state => state.list3}, namespace='list3'> <List query={QUERY3} /> </SubspaceProvider> </div> ) } 

You'll also need to namespace your reducers, you can see how to do that here.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.