Next.js Discord

Discord Forum

Loading data with useEffect and server actions?

Answered
American Shorthair posted this in #help-forum
Open in Discord
American ShorthairOP
Is this an acceptable to data fetch in a "use client" component. What's safe and what's not is still confusing to me. Will this convert this code into use client code despite having "use server" at the top of the server action page? Or is this an acceptable way to load data into a page?

till now i've been loading data in parent "server components" using the same server actions and passing them down through props. But i'm trying to find a better way now to call and use data. Especially on initial load.

The following is working, but is it secure. And if it's secure, is it recomended method or is there something better i'm missing.

Thank you in advance for your time. I appreciate it.

  useEffect(() => {
    setLoading(true);
    const fetchProgramsData = async () => {
      try {
        const userProgramDatabase = await getActiveUserProgramByUserId(user.id);
        setUserProgramData({ program: userProgramDatabase });
      } catch (error) {
        console.error('An error occurred while fetching data:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchProgramsData();
  }, []);
Answered by averydelusionalperson
const MainPage = async ({
  searchParams,
}: {
  searchParams: Record<string, string>;
}) => {
  const activeTab = searchParams["aTab"] ? searchParams["aTab"] : "";

  const data = await getTabData(activeTab);

  return (
    /// your code
  )
};


/// client component
const TabsContainer = () => {
  const onTabsChange = (tab) => {
    router.push(`?aTab=${tab}`, {
      scroll: false,
    });
  };

  return (
    ///// your code
  )
};
View full answer

26 Replies

I'm not sure about it being secure or not, as I haven't used it in useEffect yet.
but may I ask, why useEffect ?
@averydelusionalperson but may I ask, why `useEffect` ?
American ShorthairOP
Maybe I did something wrong, but i tried to do it without useEffect and it didnt seem to work
server actions isn't really supposed to fetch/get data
it is used for an action
you use server components to directly fetch data
American ShorthairOP
Yeah server omponents have been super confusing to me because I want to use a lot of the use client features (like useState etc etc) in my components
const serverComponent = async () => {
  const data = await db.get.some.data();

  return (
    <ClientComponent data={data} />
  )
};
you fetch data in server component
you do interactive stuff in client component
and you mostly use server actions in client components
Original message was deleted
please create a different thread
and delete this message
@averydelusionalperson please create a different thread
Northeast Congo Lion
ok
American ShorthairOP
So my current thing i'm trying to acomplish is this. I have tabs (mui). and ideally i woud like to not fetch the data till that tab is loaded. So i hae this structure

page (server component)
----- view that contains the tabs and loads the pages the tabs load (use client)
------------ edit tab (this is where i'm loading the data in use effect)

i did the use effect approach because I wasnt sure how to load the data only when that tab was selected. I could load it server component (at the "page") but while not a big deal with my app. Hypetheticly if i was trying to make it more database efficient I assumed I woudlnt want to load data for a tab that likely wont be visted
American ShorthairOP
hmm. not sure how to do taht but I can look into it. But basicly is that like, I'll manipulate the visual URL despite not realy going anywhere (just loading a new tab) and the parent client component (page) can pick that up and execute the query and pass it down through the three through props?
const MainPage = async ({
  searchParams,
}: {
  searchParams: Record<string, string>;
}) => {
  const activeTab = searchParams["aTab"] ? searchParams["aTab"] : "";

  const data = await getTabData(activeTab);

  return (
    /// your code
  )
};


/// client component
const TabsContainer = () => {
  const onTabsChange = (tab) => {
    router.push(`?aTab=${tab}`, {
      scroll: false,
    });
  };

  return (
    ///// your code
  )
};
Answer
^ maybe this helps
American ShorthairOP
nice. yeah i'll definitly give this a shot. tomorrow. Thank you, i appreciate it 🙂
Glad I can help, if your problem is solved, consider marking answer as solution
American ShorthairOP
Will do! I'll test it out tomorrow, it's getting late for me, and return once i have. thank you very much 🙂