Home > OS >  I want to pass my fetch results to setState. When I console.log(setUserApartment) it doesn't sh
I want to pass my fetch results to setState. When I console.log(setUserApartment) it doesn't sh

Time:01-21

import {
  useState,
  useEffect
} from "react"
import apiUrl from "../../../apiConfig"

const UserApartments = (props) => {

    // get an apartment by Id
    const [userApartment, setUserApartment] = useState([])
    useEffect(() => {
      getUserApartment()
    }, [])

    const getUserApartment = () => {
      const requestOptions = {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${props.user.token}`
        },
      }
      console.log('USER APARTMENTS', setUserApartment)

      fetch(`${apiUrl}/apartments/user/${props.user._id}`, requestOptions)
        .then(res => res.json())
        .then(foundApartments => {
          console.log('THESE ARE THE USER APARTMENTS', foundApartments)
          console.log('USER APARTMENTS SET TO STATE', setUserApartment)
          setUserApartment(foundApartments)
        }, [])
        .catch(err => console.log(err))
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

My console log for foundApartments shows {apartments: Array(2)}, then apartments: Array(2), then 0:{_id: '61df0f312c26cb6a5d0db105', owner: '61df0f162c26cb6a5d0db100'}, then 1: {_id: '61e0bdf21053bb04c6776167', owner: '61df0f162c26cb6a5d0db100'}, length: 2. Which is what it should show as that user has only created 2 apartment listings. I want to setState so I may use this component as a prop for editing user apartments. Should I pass the data from my fetch call to setUserApartment? Should the console log for foundApartments and setUserApartment show the same information if data is passed correctly to setUserApartment? I'm a new developer so please let me know if more context is needed. Thanks

CodePudding user response:

You're console logging the function to set the state. You need to console log the state to see what's in it rather than the function to set the state.

console.log('USER APARTMENTS', userApartment)

instead of

console.log('USER APARTMENTS', setUserApartment)

CodePudding user response:

You are setting state correctly via setUserApartment(foundApartments). If you add the state value to the JSX returned by the component:

<>{userApartment}</>

you'll see it. You could also test this by adding another effect (just for testing purposes) that will run whenever the state changes:

useEffect(() => {
    console.log("state has changed", userApartment);
}, [userApartment]);

Note that the state value is asynchronously set, so you can't reliably print it to the console straight after setting it.

The first value you are printing

console.log('THESE ARE THE USER APARTMENTS', foundApartments)

will print the correct value returned by your fetch request.

Now the other log:

console.log('USER APARTMENTS SET TO STATE', setUserApartment)

is printing the function passed to useEffect to set the state.

CodePudding user response:

import {
  useState,
  useEffect
} from "react"
import apiUrl from "../../../apiConfig"

const UserApartments = (props) => {

    // get an apartment by Id
    const [userApartment, setUserApartment] = useState([])
    useEffect(() => {
      getUserApartment()
    }, [])

    const getUserApartment = () => {
      const requestOptions = {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${props.user.token}`
        },
      }
      console.log('USER APARTMENTS', setUserApartment)

      fetch(`${apiUrl}/apartments/user/${props.user._id}`, requestOptions)
        .then(res => res.json())
        .then(foundApartments => {
          console.log('THESE ARE THE USER APARTMENTS', foundApartments)
          console.log('USER APARTMENTS SET TO STATE', userApartment)
          setUserApartment(foundApartments)
        })
        .catch(err => console.log(err))
    }
    const userApartmentList = userApartment.apartments.map((item) => {
          return <li > {
            item.title
          } < /li>})
          console.log(userApartmentList)
          console.log('USER CREATED APT', userApartment)

          return (

            <
            div >


            {
              userApartmentList
            }

            <
            /div>

          )
        }

        export default UserApartments
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

After reading the response from David clarifying that state was being passed correctly and that I needed to console log useState instead of setState. I then mapped through userApartment and saved it to the variable userApartmentList. Then returned userApartmentList as JSX

  •  Tags:  
  • Related