Home > Back-end >  Data is not displayed from the array on page load
Data is not displayed from the array on page load

Time:01-21

I have made an array which stores the data of the items from my API and tried displaying it in my page.

But the items are not loading on the page.

the array which has the items is this

const allCategory = ["All",...new Set(filteredData.map((curElem)=> {return curElem.Category}))];

In this way I'm displaying the items from the array:


 const [catItems, setCatItems] = useState(allCategory);


    const filterItem = (category) =>{

        if(category === "All"){
            setData(mainArray);
            return;
        }

        const updatedItems = mainArray.filter((curElem)=>{
            return curElem.Category === category;
        })
        setData(updatedItems);
    }
<div>
{
 catItems.map((curClem, index)=>{
    return <li key={index} onClick={() => filterItem(curClem)}>{curClem}</li>
                        })
                    }
</div>

When I tried loading the array in use effect and the complete page goes blank :

useEffect(() => {
        async function fetchData(){
          try {
            const response = await fetch('https://63b6952d1907f863aafa9342.mockapi.io/menu/')
            const data = await response.json();
            setData(data);
            setMainArray(data);
            setCatItems(data);
          } catch (error) {
            console.error(error);
          }
        }
    
        fetchData();
      }, []);

I think I'm making a mistake while loading the array in use effect.

Tell me what is the issue I'm facing or the error I made in my code and help me with solving it.

My data from array is not displayed on page and I tried calling them in use Effect but it is not working. I think I'm making a mistake in calling the set state in use Effect.

I'm providing the sandbox link for further details in my code:

Edit data-is-not-displayed-from-the-array-on-page-load

  • Related