Home > Enterprise >  Getting value from redux selector javascript
Getting value from redux selector javascript

Time:12-07

I am calling an endpoint that returns an object to my redux store. The redux selector for that object returns:

Coin selector:  
{zynecoin: {…}}
zynecoin: {usd: 0.214749}
[[Prototype]]: Object

This is the component:

const ChartModal = (props) => {
  const coinSelector = useSelector(selectCoin);
  let coinValuesEnt = [];
  let coinValuesVal = [];

  React.useEffect(() => {
    if (coinSelector !== undefined) {
      coinValuesEnt = Object.entries(coinSelector);
      coinValuesVal = Object.values(coinSelector);
      console.log("Coin selector: ", coinSelector);
      console.log("Object.entries: ", coinValuesEnt[0]);
      console.log("Object.values: ", coinValuesVal[0]);
    }
  }, [coinSelector]);

  const style = {
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    width: 400,
    bgcolor: "background.paper",
    border: "2px solid #000",
    boxShadow: 24,
    pt: 2,
    px: 4,
    pb: 3,
  };

  return (
    <Modal
      hideBackdrop
      open={props.openModal}
      onClose={props.handleModalClose}
      // aria-labelledby="child-modal-title"
      // aria-describedby="child-modal-description"
    >
      <Box sx={{ ...style, width: 300 }}>
        <h3>Coin: {props.coinText}</h3>
        <h3>
          Price: 
          {/* {JSON.stringify(coinSelector).substring(
                    JSON.stringify(coinSelector).lastIndexOf(":")   1,
                    JSON.stringify(coinSelector).length - 2
                  )} */}
        </h3>
        <CandleStickChart />
        <Button onClick={props.handleModalClick1}>Show Full Chart</Button>
        <Button onClick={props.handleModalClick2}>Add to Portfolio</Button>
      </Box>
    </Modal>
  );
};

I have tried inputting the selector to Object.values and Object.entries in my useEffect and when the useEffect runs the 3 console.logs return:

Coin selector:  {zynecoin: {…}}zynecoin: {usd: 0.214749}[[Prototype]]: Object

Object.entries:  (2) ['zynecoin', {…}] 0: "zynecoin" 1: {usd: 0.214749} length: 2
[[Prototype]]: Array(0)

Object.values:  {usd: 0.214749}usd: 0.214749[[Prototype]]: Object

I need only the number specified by the usd key and I have tried various methods such as:

coinValuesVal[0].usd
coinValuesVal[0][0]
coinValuesEnt.usd
coinValuesEnt[1]

and they cause compile errors of usd undefined, [0] undefined, etc. The only way I have been able to pull the price number only is the commented out section in my h3 tag which does not seem like the right way to do it. What am I doing wrong?

CodePudding user response:

So two parts of the problem,

  • you want the keys of zynecoin which apparently when accessed just returns { usd: <price> }
  • you want the value of the said key, in this case usd

To get the key usd of the object zynecoin,
Object.keys(coinSelector.zynecoin)[0] ( returns an array of keys in which since only usd exists. We just need the first one. )

To get the value, you know it should be as straightforward as,
coinSelector.zynecoin.usd

If you're getting issues because of undefined. There's no other ways around it. You have to put a ternary operator to check whether or not coinSelector.zynecoin exists.

{
  coinSelector.zynecoin && <Price code goes here>
}

Or if you're using latest ES, use optional chaining. (but that would still show an empty price)

PS: useEffect resolves after render. So if that selector from the moment your component mounts is undefined, it will go with undefined first. You don't need to use that hook for derived state. Just put the code outside the hook.

  • Related