Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next JS: Right way to fetch client-side only data in a Functional Component

I have a functional component. Basically, the page consists of a form - where I need to populate some existing data into the form and let the user update it.

I'm using a hook that I wrote to handle the forms. What it does is this

 const [about, aboutInput] = useInput({
    type: 'textarea',
    name: 'About you',
    placeholder: 'A few words about you',
    initialValue: data && data.currentUser.about,
  })

about is the value and aboutInput is the actual input element itself. I can pass an initialValue to it too.

At the beginning of the component I'm fetching the data like so:

const { data, loading, error } = useQuery(GET_CURRENT_USER_QUERY)

This only is executed on the client side and on the server side data is undefined.

Hence this code only works when I navigate to the page through a Link component from another client-side page.

It doesn't work for:

  1. When I go the URL directly
  2. When I navigate to this page from another SSR page(which uses getInitailProps)

I don't want to use lifecycle methods/class component(since I'm using hooks, and want to keep using the functional component.

Is there a nice way to achieve this in Next JS and keep using functional component?

like image 737
Sooraj Avatar asked Oct 24 '25 02:10

Sooraj


1 Answers

You can fetch client-side only data using the useEffect Hook.

Import it first from react

import { useEffect } from 'react';

Usage in the component looks like follows

useEffect(() => {
  return () => {
    // clean-up functions
  }
}, []);

The first argument Is a function and you can make your API calls inside this.

The second argument to the useEffect will determine when the useEffect should be triggered. If you pass an empty array [ ], then the useEffect will only be fired when the component Mounts. If you want the useEffect to fire if any props change then pass such props as a dependency to the array.

If you want GET_CURRENT_USER_QUERY from the query string you can pass the argument from the getInitailProps and read this as props in the useEffect array dependency.

like image 163
visizky Avatar answered Oct 26 '25 17:10

visizky