I’ve built a custom block that takes values from apiFetch and maps them into an array of attributes. The problem is I think the custom block has cached on the system so the attribute array isn’t updating with the values. Here is the code.
Edit.js is where I am mapping the values and the function adds to the array
const { backgroundColor, textColor, selectedValue, myNumber, menuItems } = attributes;
...
function upadateMenuItems (src, heading, para, href, index){
const updateMenuItems = [...menuItems];
updateMenuItems[index] = { src: src, heading: heading, para: para, href: href };
setAttributes({ menuItems: updateMenuItems });
console.log(menuItems);
}
...
<p class="blog-stamp-parent">
{newArray.filter((m, idx) => idx < myNumber && m.catagory == selectedValue).map((m) => {
return (
<div class="blog-stamp">
<img src={m.image} width="200" height="200" />
<RichText
tagName="h3"
class="stamp-title"
onChange={(heading) => upadateMenuItems(src, heading, para, href)}
value={m.label}
/>
<RichText
tagName="p"
class="stamp-excerpt"
onChange={(para) => upadateMenuItems(src, heading, para, href)}
value={m.content}
/>
<p class="button-parent">
<a
href={m.link}
className="sfs-button"
style={{ backgroundColor: backgroundColor, color: textColor }}
>
{'Read more'}
</a>
</p>
</div>)
})}
</p>
block.json converts the values into an array of attributes
"attributes": {
"content": {
"type": "string",
"source": "html",
"selector": "h2"
},
"menuItems":{
"type":"array",
"source": "query",
"selector": "div",
"query" : {
"src": {
"type":"string",
"source": "attribute",
"selector": "img",
"attribute": "src"
},
"heading": {
"type": "string"
},
"para": {
"type": "string",
"selector": "p",
"source" : "text"
},
"href": {
"type":"string",
"source": "attribute",
"selector": "a",
"attribute": "href"
}
}
}
},
Save.js is where it takes the menuItems array and renders it on the website
import { useBlockProps } from '@wordpress/block-editor';
export default function save({attributes}) {
const { backgroundColor, textColor, selectedValue, myNumber, menuItems } = attributes;
const mapFile = menuItems.map(({src, heading, para, href}) => {
return (
<div class="blog-stamp"><img src={src} width="200" height="200" /><h3 class="stamp-title">{heading}</h3><p class="stamp-excerpt">{para}</p><p class="button-parent"><a href={href} class="sfs-button" style={{ backgroundColor: backgroundColor, color: textColor }}>Read more</a></p></div>) });
return (
<div{ ...useBlockProps.save() }>
<p class="blog-stamp-parent">{mapFile}</p>
</div>
);
}
It was working but now isn’t so think its cached. I’ve been trying to solve it for the last 2 days but can’t figure it out so any help will be appriciated.
Thanks in advance.