Search code examples
reactjsasynchronousreduxredux-thunkreact-table

Passing Dispatch to a non component that sets columns of ReactTable?


I am using React Redux and Thunk for my front end Application. I have used ReactTable to render table views. ReactTable accepts columns and data as props. Since I have data coming from graphQL server I have to make a call for getting data. So I have an action that gets data from server and I am making a delayed dispatch for that action using thunk. Now the problem is since my headers and table data are coming from my action that is in a separate file other then component and I want to access dispatch right inside my header because I have rendered custom cells where I have icons to delete my table rows and I want to dispatch getData action after deleting any item so that my table updates how can i access dispatch in a non component file where I can not call connect ?


Solution

  • You can pass down fetchTableData to the <Table> and to <Header /> components. e.g.

    <TableContainer />

    const mapStateToProps = (state) => ({
        hasError: hasError(state),
        isLoading: isLoading(state),
        tableData: getTableData(state),
    });
    
    const mapDispatchToProps = {
      fetchTableData,
    };
    
    export default connect(
        mapStateToProps,
        mapDispatchToProps
    )(Table);
    

    <Table />

    export default class Table extends Component {
        componentDidMount() {
            // fetches table and header data for the first time when Table mounts
            this.fetchTableData();
        }
        render() {
            return (
              <div>
                // passes the fetchTableData function to Header so it can 
                // refetch the data when something is deleted
                <Header fetchTableData={props. fetchTableData}/>
                <Body />
              </div>
            );
        }
    }
    

    You can also consider:

    1. Connecting <Header /> to state as well and setting up its on dispatch actions.
    2. Not refetch all data from API on delete. If delete was successful, simply dispatch an action to remove the deleted row from Redux state.