Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get state of _app.js in Next.js?

I have initiated a state in _app.js using Next.js. I would like to use this state in the index.js file. How can I access it?

This is my _app.js code:

import React from 'react';
import App, { Container } from 'next/app';
import Layout from '../components/Layout';

export default class MyApp extends App {
  constructor(props) {
    super(props);
    this.state = {
      currencyType: {
        name: 'Ether',
        price: 1,
      },
      ethPriceUsd: 1,
    };
  }

  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {};
    let ethPriceUsd;

    if (Component.getInitialProps) {
      fetch(`https://api.coingecko.com/api/v3/coins/ethereum/`)
        .then((result) => result.json())
        .then((data) => {
          ethPriceUsd = parseFloat(data.market_data.current_price.usd).toFixed(
            2
          );
        });
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps, ethPriceUsd };
  }

  componentDidMount() {
    const ethPriceUsd = this.props.ethPriceUsd;
    this.setState({ ethPriceUsd });
  }

  onCurrencyTypeChange(currencyTypeValue) {
    let currencyType = {};
    //Value comes from Header.js where Ether is 0 and USD is 1
    if (currencyTypeValue) {
      currencyType = {
        name: 'USD',
        price: this.state.ethPriceUsd,
      };
    } else {
      currencyType = {
        name: 'Ether',
        price: 1,
      };
    }
    alert('We pass argument from Child to Parent: ' + currencyType.price);
    this.setState({ currencyType });
  }

  render() {
    const { Component, pageProps } = this.props;
    return (
      <Container>
        <Layout changeCurrencyType={this.onCurrencyTypeChange.bind(this)}>
          <Component {...pageProps} />
        </Layout>
      </Container>
    );
  }
}

A lot of it is irrelevant (Like passing the data to the Layout etc...). All I want to do is use this state in my index.js.

like image 787
Contentop Avatar asked Dec 04 '18 02:12

Contentop


People also ask

Can we use state in next JS?

The useState Hook is one of the most common ways to manage the state in Next. js. We will build an application that lets you increase the count by clicking the button.

What is _APP js in Nextjs?

Note: The _app. js file is the default App component that Next. js uses to initialize pages. It serves as the starting point for all of your page's components.

How do you do state management in Nextjs?

One of the most common ways to manage state is with the useState Hook. We will build an application that lets you increase the score by clicking the button. We first imported the useState hook itself, then set the initial state to be 0 . We also provided a setScore function so we can update the score later.

How do I keep component state across pages in next JS?

In Next. js, the correct way to persist components between page changes is to use the custom App component. It's quite simple. All you have to do is to create the file /pages/_app.


1 Answers

let's say you have this code in _app.js.

import React from 'react'
import App, { Container } from 'next/app'

export default class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return { pageProps }
  }

  state = {
    name: "Morgan",
  }

  render () {
    const { Component, pageProps } = this.props

    return (
      <Container>
        <Component {...pageProps} {...this.state}/>
      </Container>
    )
  }
}

Please notice the state and <Component {...pageProps} {...this.state}/>

Solution 1:

Now, let's see how can we use it in index.js or any other pages

import React from 'react';

export default class Index extends React.Component {

  render() {
    return (
      <div>
        <h2>My name is {this.props.name}</h2>
      </div>
    )
  }
}

You can use them as props like this this.props.name

Solution 2:

Populate state in the index.js from props and then access it from state

import React from 'react';

export default class Index extends React.Component {

   constructor(props) {
       super(props)
       this.state ={
           name: this.props.name
       }
   }

  render() {
    return (
      <div>
        <h2>My name is {this.state.name}</h2>
      </div>
    )
  }
}

You can use them as props like this this.state.name

like image 130
MoHo Avatar answered Sep 18 '22 13:09

MoHo