PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 12, 2022

[FIXED] Why doesn't the axios response get saved in useState variable

 October 12, 2022     axios, react-hooks, reactjs     No comments   

Issue

I've built a random photo displaying feature in react.
the console says that the response is valid and it works,
but the page breaks when I return data.

Where is the issue? Thanks in advance!

import React from 'react'
import { useEffect, useState } from 'react'
import axios from 'axios'

function RandomPhoto() {
  const url = `https://api.unsplash.com/photos/random/?client_id=${process.env.REACT_APP_UNSPLASH_KEY}`
  const [data, setData] = useState()
  
  const getPhoto = () => {
    axios.get(url)
      .then(response => {
        setData(response.data)
        console.log(response.data) // <------- works
      })
      .catch(error => {
        console.log(error)
      })
    }
  
  useEffect(() => {
    getPhoto()
  },[])
  
  console.log("XX" + data) // <---------- doesn't work, and following return() neither

  return (
    <div>
      <img href={data.urls.regular} alt={data.alt_description}/> 
      <p>Photo by {data.username} {data.name} from {data.location} - found on unsplash</p>
    </div>
  )
}
export default RandomPhoto

Solution

I modified your code a bit, and it's working. I made it as an async function and changed the path of JSON object keys.

Please note the location data sometimes returns as null. So you have to render it conditionally.

import React from 'react';
import { useEffect, useState } from 'react';
import axios from 'axios';

const RandomPhoto = () => {
  const url = `https://api.unsplash.com/photos/random/?client_id=${process.env.REACT_APP_UNSPLASH_KEY}`;
  const [imageData, setImageData] = useState('');

  const getPhoto = async () => {
    await axios
      .get(url)
      .then((response) => {
        setImageData(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  useEffect(() => {
    getPhoto();
  }, []);

  return (
    <div>
      <p>Hello</p>
      <img src={imageData.urls?.regular} />
      <p>
        Photo by {imageData?.user?.username} {imageData?.user?.name} from{' '}
        {imageData?.location?.country} - found on unsplash
      </p>
    </div>
  );
};

export default RandomPhoto;

Example Image



Answered By - MC Naveen
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing