skip to Main Content

Whenever I write a useEffect() inside a component function of my block plugin, the edit page goes blank and the console logs the message:

react_devtools_backend.js:4026 Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at Object.it (react-dom.min.js?ver=17.0.1:9:43163)
at e.useState (react.min.js?ver=17.0.1:9:10899)
at Prompt (Prompt.js:5:35)
at N (element.min.js?ver=3dfdc75a0abf30f057df44e9a39abe5b:2:9552)
at U (element.min.js?ver=3dfdc75a0abf30f057df44e9a39abe5b:2:10502)
at N (element.min.js?ver=3dfdc75a0abf30f057df44e9a39abe5b:2:9284)
at lr (blocks.min.js?ver=658a51e7220626e26a92a46af5c2e489:3:111294)
at blocks.min.js?ver=658a51e7220626e26a92a46af5c2e489:3:137935
at xn (blocks.min.js?ver=658a51e7220626e26a92a46af5c2e489:3:138073)
at blocks.min.js?ver=658a51e7220626e26a92a46af5c2e489:3:139086

The component:

import React, { useState, useEffect } from "react";
import axios from "axios";

function Prompt(props) {
  const [data, setData] = useState({ hits: [] });

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        "http://my-site-test.local/wp-json/wp/v2/posts?_fields[]=title"
      );

      setData(result.data);
    };

    fetchData();
  }, []);

  console.log(data);

  return (
    <>
      JSX...
    </>
  );
}

export default Prompt;

I tried to delete node_modules and reinstall to no avail…

2

Answers


  1. Chosen as BEST ANSWER

    I believe the problem is in my-plugin/src/index.jswp.blocks.registerBlockType's 'save' property only allows static HTML to be returned (so it can be stored in the database within the content) and I was trying to insert a React component into it.

    Since I want a dynamic block on the front-end, I have to load a register_block_type in my-plugin/index.php to render my component.

    EDIT You actually can add React directly in the save attribute if you have specified script when registering your block in the PHP main file (or in your block.json file.


  2. I used to encounter this error and figured out the reason. If your block is a static block, meaning that your save function return some thing. That can be a pure HTML markup or contain some React components. But remember, these React components must be resolved as static HTML, that means you are not allowed to put any kind of hooks inside it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search