简体   繁体   中英

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

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?

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();
}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM