btholt / complete-intro-to-react-v6

learn React.js with Brian Holt
https://frontendmasters.com/courses/complete-react-v6/
Other
1.47k stars 215 forks source link

React hooks - setState does not update state properties #38

Closed climberbrad closed 3 years ago

climberbrad commented 3 years ago

I've made it to the useEffects portion of the course. When implementing useEffect() I am not seeing the values of animal, location or breed passed to the url here

I added a console.log in the code below and the value of animal is always empty

async function requestPets() {
        console.log(`animal=${animal}`)
        const url = `http://pets-v2.dev-apis.com/pets?animal=${animal}&location=${location}&breed=${breed}`
        console.log(url)
        const res = await fetch(url);
        const json = await res.json();

        setPets(json.pets);
    }
image

I am using

npm 7.15.1
node v16.3.0

What am I doing wrong?

climberbrad commented 3 years ago

Passing animal to useEffect() allows it to populate correctly but I would love to know how to update only when you hit the submit button.

useEffect(() => {
        requestPets();
    }, [animal])  //eslint-disable-line react-hooks/exhaustive-deps
climberbrad commented 3 years ago

Looks like i just needed to make it a little further in the tutorial :)