theJuls theJuls - 1 month ago 10
React JSX Question

Using two redux actions when clicking a button

Sounds like something simple enough, but redux is just so darn confusing.

As it is now, I have a list of buttons created based off of a reducer object, and when I click one of them, I make a get request which return me an object, which I then render accordingly.

What I would like to add is the name of the button clicked and use it as a title to what is created from the get request.

Here is my current code:

//containers/module-buttons.js
//where the buttons are creared and bound to an action
//fetchLogs(moduleUrl) is with the get request I am making
class ModuleButtons extends Component{
createListItems(){
return this.props.modules.map((module)=>{
return (
<ListGroupItem bsStyle="warning" key ={module.id}
onClick={()=>this.props.fetchLogs(module.url)}>
{module.name}</ListGroupItem>
);
});
}

render(){
return (
<ListGroup>
{this.createListItems()}
</ListGroup>
);
}
}

function mapStateToProps(state){
return {
modules: state.modules

};
}

function matchDispatchToProps(dispatch){
return bindActionCreators({fetchLogs: fetchLogs}, dispatch);
}

//containers/module-log.js
//whenever a button is clicked, the json object from the get request is rendered here
//what I want to do it in the <h3> tags put the name of the button previously clicked.
class ModuleLog extends Component{

render(){
if (!this.props.module){
return <Panel><h5>Please select a module</h5></Panel>;
}
else{
const renderData = Object.keys(this.props.module)
.map((mainKey, key )=> <Log mainKey={mainKey}
innerObject={this.props.module[mainKey]} key={key} />);
return (
<div>
<h3>[insert module name here]</h3>
<ul>{renderData}</ul>
</div>
);
}
}
}

function mapStateToProps(state){
return {
module: state.moduleLog
};
}

export default connect(mapStateToProps)(ModuleLog);

// actions/actions.js
export const moduleClicked = (module) =>{
return {
type: "MODULE_CLICKED",
payload: module
}
}

export function fetchLogs(moduleUrl){
console.log(moduleUrl);
const request = axios.get(moduleUrl);
return (dispatch) => {
request.then(({data}) =>{
dispatch({type: 'FETCH_MODULES', payload: data});
});
};
}


Edit: added the code in the actions.js file.

Answer

Why not just add an extra argument to fetchLogs and then dispatch another action?

<ListGroupItem 
  bsStyle="warning" key ={module.id}
  onClick={()=>this.props.fetchLogs(module.url, module.name)}>
    {module.name}
</ListGroupItem>

And hence:

//actions.js

export function fetchLogs(moduleUrl, moduleName){
    console.log(moduleUrl);
    const request = axios.get(moduleUrl);
    return (dispatch) => {
        request.then(({data}) =>{
            dispatch({type: 'FETCH_MODULES', payload: data});
            dispatch({type: 'MODULE_CLICKED', payload: moduleName});
        });
    };
}