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

209
Visualizações
React, how to memoize API Data called in reusable component?

I have a component that opens the dialog to provide inputs:

function App() {
  const [toggle, setToggle] = useState(false);
  return (
    <>
      <button onClick={setToggle(true)}>Show Dialog</button>
    </>
  );
}

export default App;

This is the dialog component which is opened:

function Dialog() {

  return (
  <>
   <span>
     <div> Name: </div>
     <input type="text" />
   </span>
  <span>
     <div> Select: </div>
     <SelectionBox/>
   </span>
  </>
  );
}
export default Dialog;

Selection box component code is as following:

function SelectionBox() {
  const [value, setValue] = useState("");
  const [options, setOptions] = useState([]);
  const apiCalls = () => {
     service.getData1().then((data) => {
       service.getData2(data).then((opt) => {
         setOptions(opt);
       }).catch((e1) => {
         console.log(e1);
       });
     }).catch((e) => {
       console.log(e);
     });
     
  };

  return (
   <>
     <Select
      label="select"
      options={options}
      value={value} 
     />
   </>
  );

}
export default SelectionBox;

Selection box component calls two APIs to get and display the data in selection box. This API call takes time and I want to call the API only once when I open the dialog box and memoize that response for further dialog box actions. This select box can be re-used at some other place also and data is going to be same at all the places. How can I achieve this?

PS: I want to call the APIs when component is mounted. Also, not open to use any libraries.

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

0

You can do that with the help of an useEffect and localStorage. On every mount, you check if there is saved data inside localStorage, if yes use it, else you call your api, and store the result inside localStorage. Something like so:

import { useEffect } from "react";
function SelectionBox() {
  const [value, setValue] = useState("");
  const [options, setOptions] = useState([]);

  useEffect(() => {
    const apiCalls = () => {
      service.getData1().then((data) => {
          service
            .getData2(data)
            .then((opt) => {
              localStorage.setItem("options", JSON.stringify(opt));
              setOptions(opt);
            })
            .catch((e1) => {
              console.log(e1);
            });
        })
        .catch((e) => {
          console.log(e);
        });
    };
    let opt;
    try {
      opt = JSON.parse(localStorage.getItem("options"));
    } catch (error) {
      console.log(error)
    }
    if (!Array.isArray(opt)) {
      apiCalls();
    } else {
      setOptions(opt);
    }
  }, []);

  return (
    <>
      <Select label="select" options={options} value={value} />
    </>
  );
}
export default SelectionBox;
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