I use useEffect for fetching data in react functional component and it must fetch data in data (useState) so the problem is the page is loaded correctly no problems in api res .
function AdminDashBoard() {
const [data, setData] = useState([]);
const [selectedOption, setselectedOption] = useState("");
const [c_options, setc_options] = useState([]);
useEffect(() => {
axios.get("http://localhost:8000/products")
.then(response => { setData(response.data.result); })
.then(
() => {
data.forEach(element => {
let options = [];
if (options.indexOf(element.category) < 0) options += { value: element.category, label: element.category };
setc_options(options);
})
}
)
.catch(err => { console.log(err) })
}, [])
function handleSelectChange(event) {
setselectedOption(event.target.value);
console.log("selected category : ")
console.log(selectedOption)
}
return (
<div class="row-fluid main">
<div className="form-group">
<label for="formControlSelect2">select category :</label>
<Select class="form-control" id="formControlSelect2" onChange={() => handleSelectChange} options={c_options} />
</div>
<span id="products"></span>
</div>
);
}
export default AdminDashBoard;
write another useEffect and put data dependency in an array and clean up second then in your useEffect becaucse that is unnesseary
useEffect(() => {
const oldDtate=[...data]
oldDtate.forEach(element => {
let options = [];
if (options.indexOf(element.category) < 0) options += { value:
element.category, label: element.category };
setc_options(options)
}, [data])