Wednesday, October 12, 2022

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

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)

No comments:

Post a Comment

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