Reputation: 353
I want to run data(all levels) that I destructured from another data(API) and display it into the dom, it works but I got an empty array when I refresh the page
With the code below I got the data
//Function to fetch the data from the API
const GetCourses = async () => {
const response = await axios.get(url)
const {data} = response;
return data;
}
//UseEffect to run the function on every render
useEffect(()=> {
const GetCoursesYoga = async () => {
const result = await GetCourses();
setYogaCourses(result);
setTimeout(() => {setIsLoading(false)}, 1000);
}
GetCoursesYoga();
}, []);
From the data above I want to get all the items with name of levels(beginner-intermidate)
const allLevels = [ ...new
Set(yogaCourses.map((singleLevel)=>
singleLevel.level))];
I got an array of a specific item from the array that I want to store in the state below
const [levels, setLevels] = useState([]);
useEffect(()=> {
setLevels(allLevels);
},[])
How I can store the array allLevels in my state setLevels ? assuming that yogaCourses is in state
Thank you
Upvotes: 0
Views: 59
Reputation: 302
When you get the result from the API, you can set it directly to your useState
useEffect(()=> {
const GetCoursesYoga = async () => {
const courses = await GetCourses();
setYogaCourses(courses.map(course => course.level));
setTimeout(() => {setIsLoading(false)}, 1000);
}
GetCoursesYoga();
}, []);
Assuming that you have this as well:
const [yogaCourses, setYogaCourses] = useState([])
Also,setTimeout(() => {setIsLoading(false)}, 1000);
is not really great.
What we can do is wait until we actually get the result and when we set the useState
. So when our courses
go from []
=> ['course1', 'course2'...]
etc.
So what we can do is this: (When our yogacourses change value, and if that value is greater than 0, we assume we have some responses and we can stop loading)
useEffect(()=> {
if(yogaCourses.length > 0){
setIsLoading(false)
}
}, [yogaCourses]);
Upvotes: 1