I'm having an issue when i'm trying to present a list of countries that i get from the people array i have from the localStorage.
When i refresh the page I do not receive the list ,but when I change something in my code and save it, i do get the list.
I have added the code ,I'm referring to the function getCountries inside of the useEffect where i'm getting all of the countries,getting a unique array sorting it and then saving it to the state.
appreciate any help
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { loadPeople, removePerson, setFilterBy } from '../cmps/store/people.action.js';
import { PeopleList } from '../cmps/PeopleList';
import Filters from '../cmps/Filters.jsx';
export const RecipePage = () => {
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(6);
const [countries, setCountries] = useState([]);
const peoples = useSelector((state) => state?.peopleModule?.peoples);
const dispatch = useDispatch();
useEffect(() => {
const getCountries = async () => {
const countryArray = await peoples.map((person) => {
return person.location.country;
});
const uniqueCountryArray = [...new Set(countryArray)];
const sortedArray = uniqueCountryArray?.sort((a, b) => a.localeCompare(b));
setCountries(sortedArray);
};
getCountries();
}, []);
useEffect(() => {
dispatch(loadPeople());
}, []);
const onHandleRemovePerson = (id) => {
dispatch(removePerson(id));
};
const onChangeFilter = (filterBy) => {
dispatch(setFilterBy(filterBy));
dispatch(loadPeople());
};
return (
<>
<div className='main-layout'>
<Filters countries={countries} onChangeFilter={onChangeFilter} />
<PeopleList peoples={currentPost} onHandleRemovePerson={onHandleRemovePerson} />
<Pagination postsPerPage={postsPerPage} totalPosts={peoples.length} paginate={paginate} />
</div>
</>
);
};
Try adding peoples as dependency
useEffect(() => {
const getCountries = async () => {
const countryArray = await peoples.map((person) => {
return person.location.country;
});
const uniqueCountryArray = [...new Set(countryArray)];
const sortedArray = uniqueCountryArray?.sort((a, b) => a.localeCompare(b));
setCountries(sortedArray);
};
getCountries();
}, [peoples]);
when sorting and setting the array, state doesnt understand it as a change, when you use spread operator it will work fine.
setCountries([...sortedArray]);
I also faced similar situation when page was not showing list on refresh.
Later I figured out that, I missed to mention the states on which page should be rendered again.
Ex:
useEffect(() => {
},[state1, state2]);
This solved my issue and I got the list.