Advice generator app solution - React/Babel - SASS
Design comparison
Solution retrospective
Hello,
It was my first project using udeEffect hook. Its fetching two times the advise object and I don't figure out why. Someone can help me?
Community feedback
- @Ayman-Shakil192Posted over 1 year ago
Hey Leandro! 👋
Amazing job completing the challenge! Your solution looks amazing!
Now to answer your query , The reason why your code is fetching the advice object twice is because of the initial value of the get state variable which is set to 1.
When the component mounts, the useEffect hook is triggered, sending a GET request to the specified URL and updating the data state variable with the response data. This also triggers a re-render of the component.
When the component re-renders, the get state variable is incremented by 1 with setGet(c => c + 1). This causes the useEffect hook to run again, triggering another GET request to the API and another update to the data state variable, followed by another re-render.
To fix this, you can set the initial value of the get state variable to 0. This will cause the useEffect hook to only run once on the initial mount of the component, and not on subsequent re-renders. Here's the updated code snippet
const [get, setGet] = React.useState(0); // set initial value to 0
Marked as helpful0 - @Leandr0SmSPosted over 1 year ago
Thanks,
I update the code, but it keeps rendering twice... I realized that the app renders while the fetch() promise is pending, after getting data from the API it renders again with the new data state. I don't know how to avoid the component to renders twice, maybe creating a promise that waits for the API to send the data. 👋
0
Please log in to post a comment
Log in with GitHubJoin our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord