-1

I'm trying to send a GET request to http://localhost:8080/api/RE/template/${pageId} to display template items that belong to a specific id of the page. This is what displays on the console,

enter image description here

TemplateRealEstate.js

const TemplateRealEstate = () => {

  const [loadedTemplates, setLoadedTemplates] = useState([])

  const pageId = useParams().pageId;

  const getTemplates = async () => {
    await axios({
      method: "GET",
      url: `http://localhost:8080/api/RE/template/${pageId}`,
      headers: "Content-type: application/json"
    })
      .then((res) => {
        console.log("Respond from the request -->", res)
        setTimeout(() => setLoadedTemplates(res.data.templates), 0);
        console.log("Res.data.templates -->", res.data.templates)
      })
      .catch((err) => {
        console.log(err)
      })

    console.log("Loaded Templates --> ", loadedTemplates)

  }

  useEffect(() => {
    getTemplates();
  }, [pageId])
    
 }

So far I tried, using useCallback, setTimeout. I tried to add loadedTemplates as a dependency to useEffect to render the page but then it renders infinite. It displays literally infinite console.logs. If I leave the dependencies empty, it still continues the same.

Since I have files in the form, normally I make a POST request as 'Content-Type': 'multipart/form-data'. I've also tried to change the headers in the GET request but still the same. Why this is happening? I've other GET requests that didn't have this problem at all.

yuroni
  • 65
  • 6
  • 1
    In the line ``` console.log("Loaded Templates --> ", loadedTemplates) ``` loadedTemplates still has the value loadedTemplates had when the function was instantiated. – Nicolas Castellanos Dec 21 '22 at 02:42
  • What do you want to do with loadedTemplates? – Nicolas Castellanos Dec 21 '22 at 02:45
  • 1
    this is a common problem that new dev doesn't know. React state doesn't change immediately after you call `setSate` function. their updates are asynchronous. [more on that](https://blog.logrocket.com/why-react-doesnt-update-state-immediately/) – Layhout Dec 21 '22 at 02:47
  • loadedTemplates like houses. So this is a Real Estate portfolio site, every loadedTemplates object is an array that contains, images, price etc. Later, I wanted to display in the ``. – yuroni Dec 21 '22 at 02:49
  • The error was, I was calling `` instead of ``. When I changed that, I could get the data. – yuroni Dec 21 '22 at 02:50
  • Why are you setting the content-type header? Your request has no content – Phil Dec 21 '22 at 03:53

3 Answers3

1

The update will be reflected in the next render. That's how react works by design.

Take this example:

const getTemplates = () => {
    console.log(loadedTemplates) // Current state

    axios({
      method: "GET",
      url: `http://localhost:8080/api/RE/template/${pageId}`,
      headers: "Content-type: application/json"
    }).then((res) => {
      setLoadedTemplates(res.data.templates);
      console.log(loadedTemplates) // This won't print the recently updated state, but the same it printed at the beginning of the function
    })
}

Check this: https://stackoverflow.com/a/54069332/4898348

1

Everything you did is correct, except for the line

console.log("Loaded Templates --> ", loadedTemplates)

Because useState is an async function, it will be add to system stack to be call later. Therefore, that console.log placed there will show old value.

To show loadedTemplates value properly: move it outside so that the next render will show the correct value. for example:

...
useEffect(() => {
  getTemplates();
}, [pageId])

console.log("Loaded Templates --> ", loadedTemplates)
...
Thanh Chương
  • 160
  • 1
  • 5
  • OP already [confirmed they were just using the wrong component](https://stackoverflow.com/questions/74870781/react-usestate-does-not-set-the-value-that-receives-from-axios#comment132130213_74870781) – Phil Dec 21 '22 at 06:18
-1

Try to change

useEffect(() => {
    getTemplates();
  }, [pageId]) 

to

const location = useLocation()
useEffect(() => {
    getTemplates();
  }, [location])

Also don't forget to add location dependency from react router dom.. if you still facing any issue just lemme know. Thanks

Varun Kaklia
  • 366
  • 4
  • 9