In my react-admin
app there is a Create
component. I read that one can provide the record
property to initialize the Create
component like in the following.
const MyRecord = {
year: 2000,
name: "John Doe"
};
export const MyCreate = props => (
<Create record={MyRecord} {...props}>
<SimpleForm>
<DisabledInput source="year" />
<DisabledInput source="name" />
</SimpleForm>
</Create>
);
This works but now I'd like MyRecord
, i.e. the record
to get populated with the response from an API call. Somehting like this (pseudo-code)...
const response = API.get("/resource");
const MyRecord = {
year: response.data.year,
name: response.data.name
};
However I don't have an idea how to do this in React/react-admin.
This may only help get you close. But, one way could be to make MyCreate
a class component and dispatch the API call for the default values on componentDidMount. You may also be able to dispatch it sooner depending on the scenario. Much better ways to do this in production but as an example...
class MyCreate extends React.Component {
constructor(props) {
super(props);
// these will be our defaults while fetch is occurring.
this.state = {
record: {
year: 1900,
name: '',
id: 0
}
};
}
componentDidMount() {
//don't actually fetch in cdm
fetch('/resource').then(resp => this.setState({record: resp}))
}
render() {
return (
<Create {...this.props}>
<SimpleForm defaultValues={this.state.record}>
<DisabledInput source="year" />
<DisabledInput source="name" />
</SimpleForm>
</Create>
);
}
}
Also, alternatively to overriding record
you could use the defaultValues prop on <SimpleForm>
which is pretty much designed for this purpose.
https://marmelab.com/react-admin/CreateEdit.html#default-values