Home > front end >  Get data from API, store in state, then splice the data into a new state - React
Get data from API, store in state, then splice the data into a new state - React

Time:03-04

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

CodePudding user response:

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])

Second useEffect will fire when [data] array changes.

CodePudding user response:

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

  • Related