EarMoke
EarMoke

Reputation: 31

Passing data from Main layout to subpages in Nextjs

I'm trying to do something like this;

I have a file called /components/master_layout.js and it has the following content:

import useUser from "../data/use-user";

function MasterLayout({ children }) {

    const { data, error, mutate } = useUser();

    if ( error ) return <div>error</div>
    if ( !data && !error ) return <div>loading..</div>

    return (
        <div>
            {children}
        </div>
    )
}

export default MasterLayout

In short, this layout file returns according to the response of the useuser function.

Here is an example of a page where I use this layout:

file path and name: /pages/dashboard/index.js

import MasterLayout from "../../components/master_layout";

function Dashboard() {
    return (
        <MasterLayout>
            dashboard..
        </MasterLayout>
    )
}

export default Dashboard

Can I use useUser data from Layout in '/pages/dashboard/index.js' and my other pages?

The reason I want this is, I'm trying to do something like:

import MasterLayout from "../../components/master_layout";

function Dashboard({data}) {
    return (
        <MasterLayout>
            Welcome back, {data.username}
        </MasterLayout>
    )
}

export default Dashboard

Do I have any other choice but to pull the useUser for each page one by one and transfer it to the master layout as

Upvotes: 3

Views: 2900

Answers (1)

Sifat Amin
Sifat Amin

Reputation: 1186

You can use HOC pattern in this case. Something like

// with-data.js

import React from "react";
import useUser from "../data/use-user";

const withData = (WrappedComponent) => {
  class WithData extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        data: "",
      };
    }

    componentDidMount() {
      const { data, error, mutate } = useUser();
      this.setState({data:data});
    }

    render() {
      const { data, ...otherProps } = this.props;

      return (
        <WrappedComponent data={this.state.data}/>
      ) 
      //* See how we can enhance the functionality of the wrapped component
    }
  }

  return WithData;
};

export default withData;

Now you can use the withData,

import MasterLayout from "../../components/master_layout";
import withData from "../withData.js"

function Dashboard({data}) {
    return (
        <MasterLayout>
            Welcome back, {data.username}
        </MasterLayout>
    )
}

export default withData(Dashboard);

In fact wrapping around any component with withData, can access the data variable.

Upvotes: 1

Related Questions