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

Wednesday, October 12, 2022

[FIXED] How to pass data from an axios API inside a state using React?

 October 12, 2022     axios, javascript, reactjs     No comments   

Issue

I have an api (an arr of objects) which I need to pass into a state, so that I can then pass that data inside a component to show it on the website.

1st approach:

    // pulls the api data
    const newData = axios.get(url).then((resp) => {
        const apiData = resp.data;

        apiData.map((video) => {
            return video;
        });
    });

    // sets the state for the video
    const [selectedVideo, setSelectedVideo] = useState(newData[0]);
    const [videos] = useState(videoDetailsData);

    ...

    return (
        <>
            <FeaturedVideoDescription selectedVideo={selectedVideo} />
        </>
    )

2nd approach:

    const useAxiosUrl = () => {
        const [selectedVideo, setSelectedVideo] = useState(null);

        useEffect(() => {
            axios
            .get(url)
            .then((resp) => setSelectedVideo(resp.data))
        });
        return selectedVideo;
    }

    ...

    return (
        <>
            <FeaturedVideoDescription selectedVideo={selectedVideo} />
        </>
    )

both of these approaches don't seem to work. What am I missing here?


Solution

The correct way is to call your axios method inside the useEffect function.

const fetchData = axios.get(url).then((resp) => setSelectedVideo(resp.data)));

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

or if you need async/await

useEffect(() => {
  const fetchData = async () => {
    const response = await axios.get(url);
    setSelectedVideo(resp.data);
  }
    
  fetchData();
}, [])


Answered By - Apostolos
Answer Checked By - Cary Denson (PHPFixing Admin)
  • 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