Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

301
Visualizações
Getting value from redux selector javascript

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda