Rishabh Raghwendra
Rishabh Raghwendra

Reputation: 320

Redux is not giving updated state

I am new to Redux .I am making an Visual Workflow platform using Reactjs , Redux & React-flow. User can add a node by inputting name of node and it's type in Palette (Right side as shown in picture). I pass the new node name and it's type to Redux dispatch . Dispatching and updating the state is working fine (I have checked it by printing it on console) , state is updating but I am not getting the updated state automatically just like whenever we update a hook in Reactjs it's changes are shown wherever hook variable is used. But here it's not working like that . I am printing the updated state's length in top in middle div (where nodes are shown) it's only showing 0 even I add a new object to state.

I have searched about it on internet and found that Connect function in Redux will help , I also implemented it . But no solution .

I have been searching for it for last 2 days but can't figure out where's the problem . If anyone knows where's the problem , what I am missing/overlooking . Please let me know , it will be great help.

Graph.js (where I want state to update automatically):

import React, { useState, useEffect } from 'react';
import ReactFlow, { Controls, updateEdge, addEdge } from 'react-flow-renderer';
import { useSelector ,connect} from 'react-redux';
import input from '../actions/input';
const initialElements = [
  {
    id: '1',
    type: 'input',
    data: { label: 'Node A' },
    position: { x: 250, y: 0 },
  }]
function Graphs(props) {
  const onLoad = (reactFlowInstance) => reactFlowInstance.fitView();
  const [elements, setElements] = useState(initialElements);
  // const [state,setState]=useState(useSelector(state => state.nodeReducers))
  
  useEffect(() => {
    if (props.elements.length) {
      console.log("useEffect in", props.elements)
      setElements(els => els.push({
        id: (els.length + 1).toString(),
        type: 'input',
        data: props.elements.data,
        position: props.elements.position
      }));
      return;
    }
    console.log("outside if ",props.elements)
  }, [props.elements.length])
  const onEdgeUpdate = (oldEdge, newConnection) =>
    setElements((els) => updateEdge(oldEdge, newConnection, els));
  const onConnect = (params) => setElements((els) => addEdge(params, els));
  return (
    <ReactFlow
      elements={elements}
      onLoad={onLoad}
      snapToGrid
      onEdgeUpdate={onEdgeUpdate}
      onConnect={onConnect}
    >
      {console.log("in main", props.elements)}
      <Controls />
      <p>hello props {props.elements.length}</p>
    </ReactFlow>

  )
}
const mapStateToProps=state=>{
  return{
    elements:state.nodeReducers
  }
}
const mapDisptachToProps=dispatch=>{
  return{
    nodedispatch:()=>dispatch(input())
  }
}
export default connect(mapStateToProps,mapDisptachToProps)(Graphs);

nodeReducers.js (Reducer):

const nodeReducers=(state=[],action)=>{
      switch (action.type) {
            case "ADD":
                  state.push(...state,action.NodeData)
                  console.log("in node reducers",state)
                  return state;
            default:
                  return state;
      }
}
export default nodeReducers;

input.js(Action):

const input = (obj = {}) => {
      console.log("in action",obj)
      return {
            type: "ADD",
            NodeData: {
                  type: 'input',
                  data: { label: obj.NodeValue },
                  position: { x: 250, y: 0 }
            }
      }
}
export default input;

PaletteDiv.js (Right side palette div where I take user input):

import React, { useState } from 'react'
import '../styles/compoStyles/PaletteDiv.css';
import { makeStyles } from '@material-ui/core/styles';
import { FormControl, TextField, InputLabel, Select, MenuItem, Button } from '@material-ui/core';
import {  connect } from 'react-redux';
import input from '../actions/input';
function PaletteDiv(props) {
      const [nodename, setNodename] = useState();
      const [nodetype, setNodetype] = useState();
      const [nodevalue, setNodevalue] = React.useState('');

      const handleChange = (event) => {
            setNodevalue(event.target.value);
            setNodetype(event.target.value);
      };

      const useStyles = makeStyles((theme) => ({
            margin: {
                  margin: theme.spacing(1),
                  width: "88%"
            },
            formControl: {
                  margin: theme.spacing(1),
                  minWidth: 120,
            },
            selectEmpty: {
                  marginTop: theme.spacing(2),
            }
      }));

      const styles = {
            saveb: {
                  float: "left",
                  margin: "auto"
            },
            cancelb: {
                  float: "right"
            },
            inputfield: {
                  display: "block",
                  width: "100%",
                  margin: "0"
            }
      }
      const classes = useStyles();
      const useStyle = makeStyles(styles);
      const css = useStyle();
      return (
            <div id="myPaletteDiv">
                  <div className="heading">
                        <h1>Palette</h1>
                  </div>
                  <div className="palette">
                        <label >WorkFlow Name</label>
                        <TextField id="outlined-basic" fullwidth className={css.inputfield} variant="outlined" onChange={e => setNodename(e.target.value)} />
                        <label >Type of Node</label>
                        <FormControl variant="outlined" className={classes.formControl}>
                              <InputLabel id="demo-simple-select-outlined-label">Node</InputLabel>
                              <Select
                                    labelId="demo-simple-select-outlined-label"
                                    id="demo-simple-select-outlined"
                                    value={nodevalue}
                                    onChange={handleChange}
                                    label="Age"
                              >
                                    <MenuItem value="">
                                          <em>None</em>
                                    </MenuItem>
                                    <MenuItem value={10}>Step</MenuItem>
                                    <MenuItem value={20}>Condition</MenuItem>
                              </Select>
                              <Button variant="contained" color="primary" onClick={(e) => {
                             e.preventDefault();   
                      const node = { 
                                          NodeType: nodetype,
                                          NodeValue: nodename
                                    }
                                    props.nodedispatch(node)
                                    console.log("done dispatching")
                              }}>
                                    Add Node
                              </Button>
                        </FormControl>
                  </div>
            </div>
      )
}

const mapStateToProps = state => {
      return {
            elements: state.nodeReducers
      }
}
const mapDisptachToProps = dispatch => {
      return {
            nodedispatch: (node) => dispatch(input(node))
      }
}
export default connect(mapStateToProps, mapDisptachToProps)(PaletteDiv);

ScreenShot : enter image description here

Here you can see I have a

tag in middle div's top. It's showing "hello props 0". I want 0 (zero) to change whenever I add a node .

Thanking You

Yours Truly,

Rishabh Raghwendra

Upvotes: 1

Views: 519

Answers (2)

Dmitry Vdovichenko
Dmitry Vdovichenko

Reputation: 21

It's because your reducers must be pure functions. Reducer must work with the state, like with immutable data. You have to avoid side effects in your reducers

https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers#rules-of-reducers

I agree with the previous answer, but, as I said earlier, here we can avoid side effect like reassing:

const nodeReducers = (state = [],action) => {
      switch (action.type) {
            case "ADD":
                  return [...state, action.NodeData];
            default:
                  return state;
      }
}
export default nodeReducers;

Also, according to the best practices, highly recommended to write your action types to constants and use them in your actions and reducers instead of strings.

// actionTypes.js
export const ADD = "ADD";
// then import it in your reducer and action

Upvotes: 0

Naol Chala
Naol Chala

Reputation: 125

Don't push a data directly into a state into state, instead reassign the state using spreading operators

const nodeReducers = (state = [],action) => {
      switch (action.type) {
            case "ADD":
                  state = [...state, action.NodeData];
                  console.log("in node reducers",state);
                  return state;
            default:
                  return state;
      }
}
export default nodeReducers;

Upvotes: 1

Related Questions