0

According to my understanding, whatever is displayed in the save: function is what is shown on the page in the front end? So I am trying to query the database from my block to get information I am storing there but I cannot figure out how to use the fetch() function in the save: area.

when I change the code in save: to this the block says it contains unexpected or invalid content, but the block still works.

  save: function(props) {
    return wp.element.createElement(
      "div",
      { style: { border: "3px solid " + props.attributes.color } },
      'foobar baz'
    );
  }
})

do I have to use props here or something?

  • 1
    edit and save functions don't need to be similar at all. You could have totally different HTML in each. Does this help with what you are trying to achieve? – Alvaro Aug 16 at 20:30
  • 1
    As long as you tell your attributes where to pull their data from in the saved HTML, as Alvaro noted, you can make the save function's output whatever you need it to be - it doesn't have to match edit at all. The edit and save functions' only requirements are that they return something, and that you provide a way for them to interact with the attributes. While you're editing, it's best practice to use wp.element.createElement rather than React.createElement. – WebElaine Aug 16 at 21:35
  • ok I'll update my question, those last comments cleared up some things – brothman Aug 17 at 19:40
0

Any changes to the save property will cause issues with existing blocks because static blocks save the markup in save to the post content. If you make a change, you'll need to use the deprecated property to tell Gutenberg how to handle the differences between the save and what is in the post content. See here for the API.

For example:

registerBlockType( 'blockname', {
    //existing properties,
    deprecated: [
        {
            attributes: { // whatever your attributes were for the old version }
            save: // the old version of the save function     
         }
      ]
})

As for using the fetch() function, you should be able to use it in the function as expected before you return data but I'm not sure what the benefit would be of doing it there. What might be better, is doing it in the edit property and setting the data as an attribute of the block.

Pseudo code:

edit: ( props ) => {
    fetch() // not sure what we're getting here so...?
    .then(data => {
        if ( data.thing ) {
            this.setAttributes( { attName: data.thing } )
        }
    })

}

save: function(props) {
    return wp.element.createElement(
      "div",
      { style: { border: "3px solid " + props.attributes.color } },
      {props.attributes.attName}
    );
  }
})

Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.