FredericHeem / redux-act-async

Reduce boilerplate for redux async actions and reducers
Apache License 2.0
125 stars 22 forks source link

Dynamic state properties #14

Closed itsjimbo closed 8 years ago

itsjimbo commented 8 years ago

I am new to redux-act-async, just wondering the best way to put dynamic properties on the state, for example if I had 3 tabs to populate some data, that make a rest call with some id, they would call an api...

//example of what the state object might look like, but it should be dynamically created..
var state = {
    example: {
        tab1: {
            data:[]
        },
        tab2: {
            data:[]
        },
        tab3: {
            data:[]
        }
    }
};

And if I define some module that may look like the following...

function Resources(rest){
  return {
      getSomeData(id) {
          return rest.get('api/some/data/'+id);
      }
  }
}
function Actions(rest){
    let myactions = Resources(rest);
    return {
        getSomeData: createActionAsync('GET_SOME_DATA', myactions.getSomeData)
    }
}
function MyReducer(actions){
  return createReducer({
      [actions.getSomeData.ok]: (state, payload) => {
       //cannot reference which tab made the request here..
          return({
              data: payload
          });
      }
  }, {});
}

function Containers(actions){
    const mapDispatchToProps = (dispatch) => ({actions: bindActionCreators(actions, dispatch)});
    return {
        example(){
            const mapStateToProps = (state) =>  state => state.example;
            return connect(mapStateToProps, mapDispatchToProps)(TabsView);
        }
    }
}

export default function(rest) {
    let actions = Actions(rest);
    let containers = Containers(actions)
    return {
        actions,
        reducers: Reducers(actions),
        containers, 
        routes: (store) => Routes(containers, store, actions)
    }
}

How can I attach meta data to the REST promise so that the reducer knows which tab to set the data property?

Ideally the callback should have the request somewhere in there so one can reference the original parameters and thus set properties accordingly...

AFAIK, the reducer returns with the data as the payload, but there is not any knowledge of the id which requested it, but I am probably missing something simple.. Cheers

FredericHeem commented 8 years ago

Why not having a reducer for each tab?

itsjimbo commented 8 years ago

Sure, that would work, just wondering as a thought experiment if the tabs were created dynamically

FredericHeem commented 8 years ago

Any feedback on your problem ?

FredericHeem commented 8 years ago

I forgot to mention that the original request is available as an argument to the ok and error dispatch function. This should help you solve this issue.

itsjimbo commented 8 years ago

That works! Thanks @FredericHeem