0
import React, { useEffect, useState } from 'react';
import PropertyContext from './propertyContext';

const PropertyState = (props) => {

const [ details, setDetails ] = useState([])


useEffect(() => {
    loadDate();
    console.log(details)
}, [])

const loadDate = async () => {
    await fetch("https://realtor.p.rapidapi.com/properties/detail?listing_id=608763437&prop_status=for_sale&property_id=4599450556", {
    "method": "GET",
    "headers": {
    "x-rapidapi-key": "0cc8308c3cmshd6d30c4f229922dp1d5949jsn0ba6aa44fa54",
    "x-rapidapi-host": "realtor.p.rapidapi.com"
}
})
.then(response => response.json())
.then(response => {
    setDetails(response)
})
.catch(err => {
    console.error(err);
});
}

return (
    <>
        <PropertyContext.Provider value={[ details, setDetails ]}>
            {props.children}
        </PropertyContext.Provider>
    </>
)
}

 export default PropertyState;
 export { PropertyContext };
Jayant Patil
  • 1,537
  • 2
  • 11
  • 18
raghav
  • 1
  • 1
    I you are wondering why `console.log(details)` is not giving you the updated result, it is expected because your state update is affected by closure. Check this ans for more details: https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately/54069332#54069332 – Shubham Khatri Mar 08 '21 at 11:46

2 Answers2

0

Corrected your code and now the response is printed on UI you can check and modify your code stack blitz link here https://stackblitz.com/edit/react-mchv4a

//before passing details to this please try to print it
{JSON.stringify(details)}
// and props value= should be corrected
<PropertyContext.Provider value={[ details, setDetails ]}>
        {props.children}
    </PropertyContext.Provider>
Jayant Patil
  • 1,537
  • 2
  • 11
  • 18
  • thank you jayant. the code seems to be working, even without stringify but there is still one problem. when I try to access items of the "response" object it again throws an error. for some reason I cannot access the items in the 'details' state (only in the child component) even after the values being present in them – raghav Mar 10 '21 at 10:36
  • .then(response => { setDetails([ ...details, { address: response.address.city, price: response.price } ]) ---- when I try this code and console log it. it shows the first object empty and starts printing from second place in the array of objects – raghav Mar 10 '21 at 10:38
0
useEffect(() => {
    if (!details.length) {
          fetch('url')
            .then((json) => { setDetails(json))
            .catch(err => console.log(err))
    }
}, [details])

Hi Raghav, try passing details to useEffect hook which runs when the value of details changes. https://reactjs.org/docs/hooks-effect.html

  • hey thank you paarth. but i had already tried it before and it doesn't seem to be working with this method also – raghav Mar 10 '21 at 10:37