Slate.js getBlocks() in new api?

1.7k Views Asked by At

this is how I used to get blocks in slate text editor at version ^0.42.2.

import { Value, Block } from 'slate';

const value = loadInitialData ? Value.fromJSON(initialValue) : Value.create();

getTitle = (value) => {
    const firstBlock = value.document.getBlocks().get(0);
    const secondBlock = value.document.getBlocks().get(1);

    const title = firstBlock.text ? firstBlock.text : 'No Title';
    const subTitle = secondBlock.text ? secondBlock.text : 'No SubTitle';

    return {title, subTitle};
  }

Now it went through breaking changes, its api is completely changed and I cannot see any example how to get the node from its DOM.

I tried this but i got Error: Cannot find a descendant at path [0] in node: {"children":[],"operations":[],"selection":null,"marks":null,"history":{"undos":[],"redos":[]}}

import { Node } from "slate";
const node = Node.get(editor, [0])
console.log("node",node)

i want to select the first element of the node as the title and then save the blog to the database. I could not progress last 2 days, I read entire slate.js api, read almost all the issues in github could not figure out.

const getTitle = () => {
    const [firstBlock, secondBlock] = value;
    const title =
      firstBlock && firstBlock.type === "heading-one"
        ? firstBlock.children[0].text
        : "No title";
    const subtitle =
      secondBlock && secondBlock.type === "heading-two"
        ? secondBlock.children[0].text
        : "No subtitle";
    return {
      title,
      subtitle
    };
  };

When i wrote this i got an error saying "myValue is not iterable". then i switched to this:

const firstBlock = myValue[0];
const secondBlock = myValue[1];

now both values returned undefined. this is the value that i have on text editor:

enter image description here

1

There are 1 best solutions below

0
On

I am not sure that what you need, but you can map editor by elemnts

const arr = Array.from(Node.elements(editor));
const [elemnt, path] = arr.find(([elem, path]) => {/* search things */});

more about thate here: slate node docs