I am new to React and recently making a project filter gallery. I followed some tutorials online to make this and everythings worked as I want. But if I refresh the website, nothing is displayed on the 'all' section. I have to click on other section type buttons and then reclick 'all' so that all the work can be displayed there.
Current: The current website when the 'all' button is active after refreshing the page
Ideal: what I want it to look like when refreshing the page - displaying all the work
Below is my code: **Project file **
import Filter from './Filter';
import {useEffect, useState} from 'react';
const [data, setData] = useState([]);
const [filtered, setFiltered] = useState([GalleryData]);
const [activeButton, setActive] = useState('all');
useEffect(()=>{
setData(GalleryData);
setFiltered(data);
},[])
return (
<section className='projects' id='projects'>
<div className="project-container">
<div className="heading-project">Projects</div>
<div className="selection">
<Filter data={data} setFiltered={setFiltered} activeButton={activeButton} setActive={setActive}/>
</div>
**Filter File: **
import React, {useEffect} from 'react'
export default function Filter({setActive, activeButton, setFiltered, data}) {
useEffect(()=>{
if(activeButton === 'all'){
setFiltered(data);
return;
}
const filtered = data.filter((item)=>
item.type.includes(activeButton)
);
setFiltered(filtered);
},[activeButton]);
return (
<div className="filter-container">
<div className={activeButton === 'all' ? "active" : "list"} onClick={()=> setActive('all')}>All</div>
<div className={activeButton === 'UI/UX' ? "active" : "list"} onClick={()=> setActive('UI/UX')}>UI/UX</div>
<div className={activeButton === 'Website' ? "active" : "list"} onClick={()=> setActive('Website')}>Website</div>
<div className={activeButton === 'Coding' ? "active" : "list"} onClick={()=> setActive('Coding')}>Coding</div>
</div>
)
}
I am not sure why this issue exist as I follow exactly from this tutorial: https://www.youtube.com/watch?v=nyg5Lpl6AiM&t=572s
CodePudding user response:
setData
is async. Which means that in your useEffect
the value of data
is still an empty array []
.
You can simply use the GalleryData
as the initial value of the data
state
const [data, setData] = useState(GalleryData); // initial GalleryData
const [filtered, setFiltered] = useState(GalleryData); // removed the []
const [activeButton, setActive] = useState('all');
// useEffect(() => {
// setData(GalleryData);
// setFiltered(data);
// }, []);