Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redux + reactflow add edges through a reducer

Hi I’m still new to redux and I’m trying to manipulate the nodes in reactflow library using redux, I’ve managed to add a node through a reducer but when I try to add an edge(the link between nodes) it returns a warning
can anyone helps me with how to handle it in reducer

Link to sandbox if you want to see the code
https://codesandbox.io/s/react-flow-add-node-button-with-redux-1q2dz?file=/src/store/reducer.js

warning image

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This question is more a react-flow question than it is a redux question but the issue is that you aren’t dispatching an action with the source and target node ids you want to connect.

App: dispatch the add edge action with the vertices/node ids you want to connect:

const AddEdge = ({ source, target }) => {
  dispatch({
    type: "ADD_EDGE",
    source,
    target,
  });
};

Reducer – don’t mutate the state object, just return a new state object value:

export const reducer = (state = initialElements, action) => {
  switch (action.type) {
    case ADD_NODE:
      return [
        ...state,
        {
          id: Math.random().toString(),
          position: { x: 100, y: 50 },
          data: { label: "yo" }
        }
      ];
    case ADD_EDGE:
      return [
        ...state,
        {
          id: Math.random().toString(),
          source: action.source,
          target: action.target
        }
      ];
    default:
      return state;
  }
};

Edit react-flow-add-node-button -with-redux (forked)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading