Gutenberg setAttributes not working
-
I’m really struggling with creating a Gutenberg block since day, now.
Now the problem is this. I declared a “offers” attribute inside my block like this:attributes: { offers: { type: 'array', default: [] } },
Everytime I have to save the value for ‘offers’, setAttributes doesn’t work.
This is the function that manage the saving of the offers values. It add an ‘offerid’ to the ‘offers’ attribute everytime I click on an “Add” button or removes it if I click on a “Remove” Button.
The console.log at the end of the function returns me the correct ‘offers’ array, populated with values, but if I save the post and reload the page, the ‘offers’ array is instatiated as empty and I can’t understand why and how I could solve this problem.
export default function ButtonAdd({offerid, clicked, props}) { const { attributes: { offers }, setAttributes } = props; let [ click , setClick ] = useState(clicked); //let [ ofs, setOffers ] = useState(offers); function handleAddButton(){ const index = offers.indexOf(offerid); if(click){ index > -1 ? offers.splice(index, 1) : offers; setClick( false ) $(<code>.${offerid}-btn</code>).empty().text('Add').removeClass('btn-danger').addClass('btn-success'); } else { index < 0 ? offers.push(offerid) : offers; setClick( true ); $(<code>.${offerid}-btn</code>).empty().text('Remove').removeClass('btn-success').addClass('btn-danger'); } //setOffers( prevOffers => { return [...prevOffers, offerid] } ); setAttributes({offers: offers}); console.log(props.attributes.offers); } return ( <Button onClick={ handleAddButton } className={<code>btn btn-sm btn-success ${offerid}-btn</code>} > { click ? 'Remove' : 'Add' } </Button> ) }
P.s.: I know I should use the spread operator and not working directly on the attribute, but if I do so, every time I click on my “Add” button, it empties the array and populate it only with the new value. And still reloading the page I get the empty ‘offers’ array;
- The topic ‘Gutenberg setAttributes not working’ is closed to new replies.