Chen A.
Chen A.

Reputation: 11338

React render an image dynamically after a page reload (depends on state)

I've a react component that I try to load image dynamically. The image is dependent on a state, that is loaded from the backend with useEffect. The initial state is empty.

When I change the state (using a drop list inside the form), the image is displayed correctly but when I reload the page, the image won't show up.

What I'm trying to do is to re-render / delay the render of the the component (or just tag) after the fetch is complete. So I use loading as an indicator, and change it's value inside the useEffect after fetch returns.

But still when the page reloads the value of winner is undefined, and I get no image.

const Winner = () => {
  const [winner, setWinner] = useState({"id": "", "name": ""})
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch(`/api/v1/winner`, {
      method: 'GET',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
    })
    .then(res => res.json())
    .then(jsonData => {
      setWinner(jsonData)
      setLoading(false)
    })
    .catch((error) => {
      console.log(error)
    })
  }, [])

  return (
    (loading ? <p>Loading..</p> : 
      <Box className="bonus">
        <img src={`./static/${winner.name}.png`.toLowerCase()} width="40px" height="40px" />
        <FormControl>
        ...
        </FormControl>
      </Box>
  ))
}

Any suggestions / help is appreciated.

Upvotes: 1

Views: 622

Answers (1)

KcH
KcH

Reputation: 3502

The initial state data and the data after fetch are different

{"id": "", "name": ""}

after fetch

{"status":"success","id":"17"}

so winner doesn't have a name prop,

Alternatively you can set the initial state to null

const [winner, setWinner] = useState(null)

....

if(loading) return "loading ..."
if(!winner) return null
if(winner) return <data.../>;

Upvotes: 2

Related Questions