Home > other >  access an object from another function in React JS
access an object from another function in React JS

Time:10-10

Hi i am trying to access a variable inside arrow function which is not working

export const SAMPLEPARTNUMBER = () => {
  const classes = useStyles();
  const { data, isFetching } = useGetThicknessQuery();
  const [selectedPartNo, setSelectedPartNo] = useState();
  var partNoObj = {};
  if (!isFetching) {
    const body = data.body;
    const row1 = data.body.row_1;
    const partNo = data.body.part_no;
    partNoObj = partNo;

    return (
      <div>
        <FormControl fullWidth className={classes.part_no}>
          <InputLabel id="demo-simple-select-label">Part No</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={selectedPartNo}
            label="Part No"
            onChange={(e) => handleChange(e)}
          >
            {Object.keys(partNo).map((val) => (
              <option key={val   Math.random()} value={val}>
                {val}
              </option>
            ))}
          </Select>
        </FormControl>

      </div>
    );
  } else {
    return <div>Loading...!</div>;
  }
//Arrow function 

  const handleChange = (e) => {
    console.log("drop down selected index", e.target.value);
    setSelectedPartNo(e.target.value);
    console.log("part no_1", partNoObj);
  };
};

inside handleChange arrow function i am trying to print the partNoObj but that is not working.

CodePudding user response:

you can do this by creating a new state. you can't create a variable inside a component directly, cause whenever the component re-render it will reset the variable.


export const SAMPLEPARTNUMBER = () => {
  const classes = useStyles();
  const { data, isFetching } = useGetThicknessQuery();
  const [selectedPartNo, setSelectedPartNo] = useState();
  const [Response, setResponse] = useState();

  useEffect(()=> {
    setResponse(data);
  }, [data]);

  //Arrow function 
  const handleChange = (e) => {
    console.log("drop down selected index", e.target.value);
    setSelectedPartNo(e.target.value);
    console.log("part no_1", Response.body.part_no);
  };

    return (
     <>{!isFetching ?
       <div>
        <FormControl fullWidth className={classes.part_no}>
          <InputLabel id="demo-simple-select-label">Part No</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={selectedPartNo}
            label="Part No"
            onChange={(e) => handleChange(e)}
          >
            {Object.keys(partNo).map((val) => (
              <option key={val   Math.random()} value={val}>
                {val}
              </option>
            ))}
          </Select>
        </FormControl>
       </div> : <div>Loading...!</div>}</>
    );

};

  • Related