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

156
Visualizações
Get data from API, store in state, then splice the data into a new state - React

I'm trying to get data from an API, and store that in setData(response.data). Then I'm trying to splice that data into a new state called items. So I do setItems(data.events?.splice(lastPage, firstPage));

Somehow my items array initially is always empty, I need to refresh the site to get the info. I'm using a loading state for that, but for some reason my items don't refresh it's state. This is the code

 const [data, setData] = useState([]);
 const [isLoading, setIsLoading] = useState(true);

 const [items, setItems] = useState([]);
 const [page, setPage] = useState(1);
 const EVENTS_PER_PAGE = 10;
 const firstPage = page * EVENTS_PER_PAGE;
 const lastPage = firstPage - EVENTS_PER_PAGE;

 useEffect(() => {
   getEvents()
     .then(function (response) {
       setData(response.data);
       setItems(data.events?.splice(lastPage, firstPage));
     })
     .catch(function (error) {
       setError(error);
     })
     .finally(function (response) {
       setIsLoading(false);
     });
 }, []);

JSON: https://www.mockachino.com/c31972ec-27f7-45/events

I tried everything but I can't make it work, any help is appreciable

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

0

When you are trying to put data in state, you cannot access its new value in the same useEffect.

What you can do is:

  1. First useEffect only fetches data and put it in state;
  2. Second useEffect (you need to create it) changes state of your items
useEffect(() => {
   getEvents()
     .then(function (response) {
       setData(response.data);
     })
     .catch(function (error) {
       setError(error);
     })
     .finally(function (response) {
       setIsLoading(false);
     });
 }, []);
useEffect(() => {
  setItems(data.events?.splice(lastPage, firstPage));
}, [data, lastPage, firstPage])

Second useEffect will fire when [data] array changes.

about 4 years ago · Juan Pablo Isaza Relatório

0

1=> do not render the page until isLoading is false something like

return isLoading ? (
    <> spinner or some else < />
  ) : (
    <> your page </>

that way your page will not render until the data is loaded.

2=> also try adding the isLoading variable to the dependency array so that page re-renders when isLoading changes

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