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

Time:08-11

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:

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

CodePudding user response:

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.

CodePudding user response:

Initially your post is empty object then you are populating post via a http request which is async in nature so you are getting undefined.

You can use conditional rendering here someting like

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

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

CodePudding user response:

<img className='h-96 rounded-drawlie' src={post.postId ? "myip.com/"   post.postId   "/"   post.postId   "-normal.jpg" : "default.jpg"}></img>

you can use a placeholder image by default, such as a loading gif

  • Related