0

I'm trying to limit repeated code by moving the code that fetches data to an external file. The fetchUserInfo I'm using uses the useEffect, useState hooks and as such needs to be a "use client" component. For some reason when I try to import an external function that has "use client" react refuses to recognise the fuction and spits out: Error: (0 , fetchUserInfo__WEBPACK_IMPORTED_MODULE_2_.default) is not a function. Thanks in advance for any response.

My folder structure:

My folder structure

Component code:

import fetchUserInfo from "./fetchUserInfo"


const VideoTestimonial = ({ channelLink }) => {
    fetchUserInfo(channelLink)
    return (
        <div>
            <p>Hello world</p>
        </div>

    )
}

export default VideoTestimonial

Function code:

"use client"
import { useEffect, useState } from "react"
const API_KEY = "INSERT_KEY"

export default function fetchUserInfo(channelLink) {
    const channelId = channelLink;

    const API_URL = `https://www.googleapis.com/youtube/v3/channels?part=statistics&id=${channelId}&key=${API_KEY}`
    const PIC_URL = `https://www.googleapis.com/youtube/v3/channels?part=snippet&id=${channelId}&fields=items%2Fsnippet%2Fthumbnails&key=${API_KEY}`
    const USERNAME_URL = `https://www.googleapis.com/youtube/v3/channels?part=brandingSettings&id=${channelId}&key=${API_KEY}`

    const [username, setUsername] = useState("loading")
    const [profileImage, setprofileImage] = useState("")
    const [subCount, setSubCount] = useState("loading")

    useEffect(() => {
        fetch(API_URL)
            .then((res) => res.json())
            .then((data) => { setSubCount(Number(data.items[0].statistics.subscriberCount).toLocaleString("de-DE")) })
            .catch((error) => {
            });

        fetch(PIC_URL)
            .then((res) => res.json())
            .then((data) => { setprofileImage(data.items[0].snippet.thumbnails.medium.url) })
            .catch((error) => {
            });

        fetch(USERNAME_URL)
            .then((res) => res.json())
            .then((data) => { setUsername(data.items[0].brandingSettings.channel.title) })
            .catch((error) => {
            });
    }, []);

    return (
        {
            username: username,
            profileImage: profileImage,
            subCount: subCount
        }
    )
}

I expected the function to be imported without issues.

1 Answer 1

0

React Hooks Must be used in a react functional component and cannot be used in standalone function line your doing in fetchUserInfo

Additionally you should not be using useState and useEffect in a function that's meant to be a utility function you can move fetching logic directly inside your component

Not the answer you're looking for? Browse other questions tagged or ask your own question.