Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React.JS: Why is useState() empty at the beginning?

I try to make a GET request and that works so far. However, a different image can always be presented on the page, which is why an ID is stored directly after the request, which can then be used to catch the image via URL.

However, at the beginning there is nothing in the "post" at useState({}) so it is empty.

and so an error message like this is generated:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

GET https://myip.net/undefined/undefined-normal.jpg 404 (Not Found)

post.postId is undefined at the beginning, because there is nothing inside yet. Right after that, 1ms later, it is no longer undefined and the image is displayed.

But it is very annoying because the image is not found at the beginning and error messages appear in the console.

I hope someone can help me 🙂

import React from 'react'
import { Link, useLocation, Navigate } from 'react-router-dom'
import axios from "axios"
import { useState, useEffect } from 'react'

const Art = () => {

    const [post, setPost] = useState({})

    function useQuery() {
        const { search } = useLocation();
        return React.useMemo(() => new URLSearchParams(search), [search]);
    }

    let query = useQuery();

    useEffect(() => {
        const token = localStorage.getItem("token")
        axios.get("myip.com").then(function (res) {

            console.log("debug")

            return setPost(res.data.cnt)
        })
    }, [])

    if (query.get("id")) {
        if (post.code == "403") {
            console.log("403")
            return (
                <div><p className='text-white'>not found</p></div>
            )
        } else {

            console.log(post)

            return (
                <div>
                    <div className='container mx-7 py-9'>
                        <img className='h-96 rounded-drawlie' src={"myip.com/" + post.postId + "/" + post.postId + "-normal.jpg"}></img>

                        <p className='text-white'>{post.description}</p>
                    </div>
                </div>
            )
        }
    }

    return (
        <Navigate to="/" />
    )

}

export default Art

>Solution :

Don’t display the image until a state value is available. For example:

<div className='container mx-7 py-9'>
  { post.postId ?
    <img className='h-96 rounded-drawlie' src={"myip.com/" + post.postId + "/" + post.postId + "-normal.jpg"}/> :
    null
  }
  <p className='text-white'>{post.description}</p>
</div>

This would conditionally include the <img> element in the markup only if post.postId contains a value.

Alternatively, you could initialize the state to a postId value for some meaningful default image:

const [post, setPost] = useState({ postId: 1 });

Basically, for the initial render you either show a known image or don’t show an image.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading