Search code examples
reactjsreduxreact-reduxreact-hooks

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


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)