Search code examples
admin-on-rest

Admin on Rest onClick being called on render and not on click


The issue I am having is I have a button:

const LogActions = ({ resource, filters, displayedFilters, filterValues, basePath, showFilter, refresh, record }) => (
    <CardActions style={cardActionStyle}>
        <RaisedButton primary label="Cancel" onClick={HandleClick(record["id"])} />/>
    </CardActions>
);

This button is used in a List like so:

export const LogList = (props) => (
    <List {...props}  perPage={100} title="Logs and Reports" filters={< FileFilter/>}>
        <Datagrid>
            <TextField source="inputfile" label="Input File" />
            <TextField source="cycle" label="Cycle" />
            <TextField source="job" label="Job" />
            <TextField source="name" label="File Name" />
            <ShowButton/>
            <LogActions/>
        </Datagrid>
    </List>
);

This is the HandleClick:

const HandleClick = (id) => {
        fetch(`controller_service/archivedfiles/${id}`, { method: 'GET', body:{} })
            .then(() => {
                // do stuff
            })
            .catch((e) => {
                console.error(e);
                //error
            });
    }

Okay so my problem is that whenever I go to this page, it will create the datagrid, but while the button is being rendered it calls HandleClick which then fetches that data before I even click on the button, and when I click on the button nothing happens. Can someone explain what I am doing wrong?


Solution

  • As wesley6j said, the function gets called when you assign it with parameters. A way to avoid this is to use .bind(this,params) or wrap your HandleClick in another function like this:

    onClick={() => HandleClick(record["id"])}