EDIT: Actually looks like registerBlockType is exactly where the store is created by the name given in the meta data. Now to find where it hooks up with the state then ??
ORIGINAL:
I don’t think that’s what I’m looking for. It seems there’s an abstraction layer between wordpress and react which handles the state/store in some way which is not apparent here. The attributes are fed as props to the component which makes me think that there is a higher level redux store or something similar. I assumed that the database would only reflect what happens in that store. This is why I thought it was safe to use the components internal state freely without needing to worry about the db. But this does not seem to be the case.
I can easily work around this, so it is not currently an issue per se. But I would like to understand how wordpress is aware of the internal state of component when hitting save.
Here’s a very much simplified version of the code that I’m working on. The only two uses of setAttributes are reflected here.
import { registerBlockType } from "@wordpress/blocks";
import { Component } from "@wordpress/element";
import { useBlockProps } from "@wordpress/block-editor";
import metadata from "./block.json";
class CustomTable extends Component {
constructor(props) {
super(...arguments);
this.props = props;
this.state = {
rows: [[""]],
sortRows: {},
error: "",
};
// ...etc...
}
componentDidMount() {
let rows = this.props.attributes.rows;
this.setState({
rows: this.props.attributes.rows,
});
}
updateRows(val, row, col) {
let temp = [...this.state.rows];
temp[row][col] = val;
this.setState({ rows: temp }, () => {
////////
// HERE I AM SAVING ATTRIBUTES
////////
this.props.setAttributes({
rows: this.state.rows,
});
});
}
// add/remove rows/columns etc... all of which only affect the STATE not the ATTRIBUTES
triggerSort(rowsInCorrectOrder) {
this.setState({ rows: rowsInCorrectOrder, sortRows: {} }, () => {
this.props.setAttributes({
rows: rowsInCorrectOrder,
});
//^^^^^^
// NO MATTER IF THIS IS HERE OR NOT. IT WILL SAVE THE CORRECT ORDER TO DB.
////////
});
}
updateOrder() {
let rowsInCorrectOrder = functionWhichGetsTheRowsInCorrectOrder();
this.triggerSort(rowsInCorrectOrder);
}
render() {
return (
<div>
{this.state.rows.map((row, rowIndex) => {
return (
<div>
<input
type="number"
value={this.getCurrentValue(rowIndex)}
onChange={(e) => {
this.updateOrder(rowIndex, e.target.value);
}}
onBlur={this.triggerSort}
/>
{row.map((item, colIndex) => {
return (
<input
type="text"
value={col}
onChange={(e) => {
this.updateRows(
e.target.value,
rowIndex,
colIndex
);
}}
/>
)
})}
</div>
);
})}
</div>
);
}
}
registerBlockType(metadata, {
edit: function (props) {
return (
<div {...useBlockProps()}>
<CustomTable {...props} />
</div>
);
},
save: function (props) {
return null;
},
});
-
This reply was modified 2 years, 8 months ago by ebbec.
-
This reply was modified 2 years, 8 months ago by ebbec.