Updating state in processor

Hi! I want to connect image viewer like react-image-lightbox or react-images-viewer.
Every image-viewer plugin requires to pass prop with array of images. I decided to add array of images to global state using processor.

export const pushImagesToGallery = {
  name: "pushImagesToGallery",

  priority: 10,

  test: ({ node }) => node.component === "img",

  processor: ({ node, state }) => {
    if (node.parent.component === "noscript") return null;

    let imageObj = {
      src: node.props.src,
    };

    const result = [...state.theme.images, imageObj];

    console.log(result);

    state.theme.images = result;

    return node;
  },
};

This code works properly but it does infinite loop

How to be?

Hi @borysenko.alexander

You should never mutate the state directly from your components. You should, instead, create actions to mutate state and call those actions from your components.

Please see here.

2 Likes

@mburridge thanks for the clarification there. I think I was modifying state in one of my handlers, whereas it sounds like I need to create an action for this.

Is the theme index the only place where state modifier actions can be created? (well apart from importing a function into the index)

Hmm :thinking:, that’s a good question. @luisherranz are you able to clarify this?

1 Like

Yes, all actions should be declared in the main package export.

2 Likes

@luisherranz @mburridge Thank you for reply) I thought about using actions intuitively but there is one huge problem using actions with processors :
image

Actions does not pass to the processor function =( so it is impossible to use them

1 Like

@borysenko.alexander , @luisherranz mentioned actions in processors being bad pattern here:

but i’m not sure why. I can see how you might be stuck then!

is your processor definitely stuck in a loop, or it just adding every image to the state hence the 20 entries etc?

@codemonkeynorth it stucks in infinite loop. As previosly sayed that state should be updated from action, not the way I do it through a mutation. New question appears: how to acess to actions in processor

Why do you need those images in the state? Where else are you using them?

I have already found right solution of my problem without image storage in state. But anyway this is interesting problem - how to access actions in processor? It is not current problem anymore but research interest: HOW TO?

I guess it will depend on each use case but the main way would be inside the useEffect function of a React component that has been rendered.

processor -> inject React component -> useEffect -> trigger an action
1 Like

Quite logical) Tanks :+1: