I've researched nextjs (7) + react context for my project. My problem is how to fetch data in getInitialProps by Provider?
-
1can you please show some code with what you have tried and what didn't work?Chaim Friedman– Chaim Friedman2019-01-15 04:06:22 +00:00Commented Jan 15, 2019 at 4:06
Add a comment
|
1 Answer
Create a component called components/CounterProvider.js
import React, { Component } from 'react'
/* First we will make a new context */
const CounterContext = React.createContext()
/* Then create a provider Component */
class CounterProvider extends Component {
state = {
count: 0
}
increase = () => {
this.setState({
count: this.state.count + 1
})
}
decrease = () => {
this.setState({
count: this.state.count - 1
})
}
render () {
return (
<CounterContext.Provider
value={{
count: this.state.count,
increase: this.increase,
decrease: this.decrease
}}
>
{this.props.children}
</CounterContext.Provider>
)
}
}
/* then make a consumer which will surface it */
const CounterConsumer = CounterContext.Consumer
export default CounterProvider
export { CounterConsumer }
then in pages/_app.js use this code to use the provider and share it between all components:
import App, { Container } from 'next/app'
/* First we import our provider */
import CounterProvider from '../components/CounterProvider'
class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return (
<Container>
{/* Then we wrap our components with the provider */}
<CounterProvider>
<Component {...pageProps} />
</CounterProvider>
</Container>
)
}
}
export default MyApp
finally use it in any component like this: pages/index.js
import React, { Component } from 'react'
/* First we import the consumer */
import { CounterConsumer } from '../components/CounterProvider'
export default class index extends Component {
render () {
return (
/* Then we use our context through render props */
<CounterConsumer>
{({ count, increase, decrease }) => (
<div>
<p>Counter: {count}</p>
<button onClick={increase}>Increase</button>
<button onClick={decrease}>Decrease</button>
</div>
)}
</CounterConsumer>
)
}
}
For more info follow this example
1 Comment
Katie
This doesn't answer the question, which is specifically about how to fetch data in the provider. The examples given in this answer do not do any data fetching at all.