I'm setting up ContextApi for the first time in a production app, hoping to replace our current handling of our app configs with it. I've followed the official docs and consulted with similar issues other people are experiencing with the API, and gotten it to a point where I am able to correctly the config when I do Config.Consumer and a callback in render functions. However, I cannot get this.context to return anything other than an empty object.
Ideally, I would use this.context in lifecycle methods and to avoid callback hell, so help would be appreciated. I've double checked my React version and that I'm setting the contextType. Below is a representation of the code
config.js
import { createContext } from "react";
export default createContext();
index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Router, browserHistory } from "react-router";
import { syncHistoryWithStore } from "react-router-redux";
import Config from "../somePath/config";
// more imports
function init() {
const config = getConfig();
const routes = getRoutes(config);
const history = syncHistoryWithStore(browserHistory, appStore);
ReactDOM.render(
<Provider store={appStore}>
<Config.Provider value={config}>
<Router history={history} routes={routes} />
</Config.Provider>
</Provider>,
document.getElementById("app")
);
}
init();
someNestedComponent.js
import React, { Component } from "react";
import { connect } from "react-redux";
import Config from "../somePath/config";
#connect(
state => ({
someState: state.someState,
})
)
class someNestedComponent extends Component {
componentDidMount() {
console.log(this.context);
}
render() {
return (...someJSX);
}
}
someNestedComponent.contextType = Config;
export default someNestedComponent;
Currently running on:
React 16.8.6 (hopi to see error messages about circuitous code but
didn't get any warnings)
React-DOM 16.7.0
React-Redux 6.0.1
The problem is that someNestedComponent doesn't refer to the class where this.context is used:
someNestedComponent.contextType = Config;
It refers to functional component that wraps original class because it was decorated with #connect decorator, it is syntactic sugar for:
const someNestedComponent = connect(...)(class someNestedComponent extends Component {
...
});
someNestedComponent.contextType = Config;
Instead, it should be:
#connect(...)
class someNestedComponent extends Component {
static contextType = Config;
componentDidMount() {
console.log(this.context);
}
...
}
There are no callback hell problems with context API; this is conveniently solved with same higher-order component pattern as used in React Redux and can also benefit from decorator syntax:
const withConfig = Comp => props => (
<Config.Consumer>{config => <Comp config={config} {...props} />}</Config.Consumer>
);
#connect(...)
#withConfig
class someNestedComponent extends Component {
componentDidMount() {
console.log(this.props.config);
}
...
}
You didn't use a consumer to get the values
ref: https://reactjs.org/docs/context.html#contextconsumer
Related
I was trying to get the queries from my url pattern like localhost:3000/post?loc=100 by using useRouter() from "next/router" and fetching some data using that id from my server. It worked when I used it in a Stateless Functional Component.
But the page showing "Invalid hook call" then. I tried calling getInitalProps() of a Stateless Functional Component, but it didn't work there either and showed the same error.
Is there any rule to use this method?
I was developing a front-end using React Library and Next.js Framework.
constructor(props) {
this.state = {
loc: useRouter().query.loc,
loaded: false
};
}
Hooks can be used only inside functional components, not inside classes. I would recommend to use withRouter HOC as per next.js documentation:
use the useRouter hook, or withRouter for class components.
Or see From Classes to Hooks if you want to switch to hooks.
In general, it's possible to create a wrapper functional component to pass custom hooks into class components via props (but not useful in this case):
const MyClassWithRouter = (props) => {
const router = useRouter()
return <MyClass {...props} router={router} />
}
class MyClass...
constructor(props) {
this.state = {
loc: props.router.query.loc,
loaded: false
};
}
withRouter example
https://stackoverflow.com/a/57029032/895245 mentioned it, but a newbie like me needed a bit more details. A more detailed/direct description would be:
Function component:
import { useRouter } from "next/router";
export default function Post() {
const router = useRouter();
return (
<div>{ router.query.id }</div>
)
}
Class component equivalent:
import { withRouter } from 'next/router'
import React from "react";
export default withRouter(class extends React.Component {
render() {
return (
<div>{ this.props.router.query.id }</div>
)
}
})
I tested this out more concretely as follows. First I took vercel/next-learn-starter/basics-final/pages/posts/[id].js and I hacked it to use the router:
diff --git a/basics-final/pages/posts/[id].js b/basics-final/pages/posts/[id].js
index 28faaad..52954d3 100644
--- a/basics-final/pages/posts/[id].js
+++ b/basics-final/pages/posts/[id].js
## -4,13 +4,17 ## import Head from 'next/head'
import Date from '../../components/date'
import utilStyles from '../../styles/utils.module.css'
+import { useRouter } from "next/router"
+
export default function Post({ postData }) {
+ const router = useRouter();
return (
<Layout>
<Head>
<title>{postData.title}</title>
</Head>
<article>
+ <div>router.query.id = {router.query.id}</div>
<h1 className={utilStyles.headingXl}>{postData.title}</h1>
<div className={utilStyles.lightText}>
<Date dateString={postData.date} />
Then, I ran it as:
git clone https://github.com/vercel/next-learn-starter
cd next-learn-starter
git checkout 5c2f8513a3dac5ba5b6c7621d8ea0dda881235ea
cd next-learn-starter
npm install
npm run dev
Now when I visit: http://localhost:3000/posts/ssg-ssr I see:
router.query.id = ssg-ssr
Then I converted it to the class equivalent:
import Layout from '../../components/layout'
import { getAllPostIds, getPostData } from '../../lib/posts'
import Head from 'next/head'
import Date from '../../components/date'
import utilStyles from '../../styles/utils.module.css'
import { withRouter } from 'next/router'
import React from "react"
export default withRouter(class extends React.Component {
render() {
return (
<Layout>
<Head>
<title>{this.props.postData.title}</title>
</Head>
<article>
<div>router.query.id = {this.props.router.query.id}</div>
<h1 className={utilStyles.headingXl}>{this.props.postData.title}</h1>
<div className={utilStyles.lightText}>
<Date dateString={this.props.postData.date} />
</div>
<div dangerouslySetInnerHTML={{ __html: this.props.postData.contentHtml }} />
</article>
</Layout>
)
}
})
export async function getStaticPaths() {
const paths = getAllPostIds()
return {
paths,
fallback: false
}
}
export async function getStaticProps({ params }) {
const postData = await getPostData(params.id)
return {
props: {
postData
}
}
}
and everything seemed to be unchanged.
Tested on Next.js 10.2.2.
I am coming from a vue.js background and I have just recently started looking into react.
I have a component: PageContent.jsx and I wish to use it without constantly having to import it to be able to use it inside the render function (JSX).
In vue it is possible to globalise a component using:
Vue.component(componentName, componentObject)
Is there anything similar in react?
Hmm, there isn't any kind of "global" component in React. Each component has to be imported or passed as a prop. You have a few options if you want to avoid adding an import to each file though:
1) Create a Higher Order Component that renders the PageContent and the wrapped component.
import PageContent from './PageContent';
const withPageContent = WrappedComponent => {
return class extends React.Component {
render () {
return (
<PageContent>
<WrappedComponent />
</PageContent>
)
}
}
};
export default withPageContent;
// Usage
import withPageContent from './withPageContent';
class MyComponent extends React.Component {
render () {
return (
<div>
I'm wrapped in PageContent!
</div>
)
}
}
export default withPageContent(MyComponent);
2) Pass PageContent as a prop to a component:
import PageContent from './PageContent';
export default class App extends React.Component {
render() {
return (
<React.Fragment>
<Child1 content={PageContent} />
<Child2 content={PageContent} />
</React.Fragment>
)
}
}
// Usage
export default class Child1 extends React.Component {
render () {
const PageContent = this.props.content;
return (
<PageContent>
I'm wrapped in PageContent!
</PageContent>
)
}
}
export default class Child2 extends React.Component {
render () {
const PageContent = this.props.content;
return (
<PageContent>
I'm wrapped in PageContent!
</PageContent>
)
}
}
I very much agree with Chase's answer.
Still if you need another approach you can use the context api. You can declare in the App root, or another nested components tree, a collection of components that you want to easily access.
Here is an example with the useContext hook, but hooks is not a must. The structure is the standard create-react-app structure.
The component we would like to access globally - src/deep/Header.js:
function Header() {
return (
<h1>
I am a global component
</h1>
);
}
export default Header;
The context creation - src/global-components-context.js:
import React from 'react';
const MyContext = React.createContext(null);
export default MyContext;
The grouping of the global-components - src/global-components.js:
import Header from './deep/Header';
const contextValue = {
Header,
};
export default contextValue;
The app init file - src/index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import MyContext from './global-components-context';
import contextValue from './global-component';
ReactDOM.render(
<MyContext.Provider value={contextValue}>
<App />
</MyContext.Provider>,
document.getElementById('root')
);
Using the component without importing it - src/App.js:
import { useContext } from 'react';
import globalComponent from './global-components-context';
function App() {
const Context = useContext(globalComponent);
return (
<div className="App">
<Context.Header />
</div>
);
}
export default App;
I think this is the most global components you can have in react. Note that you still need to import the context wherever you would like to use a global component.
Also one more disclaimer, global components are very hard to test and often to reason about. I believe that is why there is no standard solution for it in react.
Hope I could help
i try do that Store objet
UserStore.js
import { observable, action } from 'mobx';
class UserStore {
constructor() {
const me = observable({
me: null,
auth: action.bound(function(me) {
this.me = me;
})
})
}
}
export default UserStore;
After this, i do that
App.js
const App = inject('routing','UserStore')(observer(class App extends Component {
constructor(props, context) {
super(props, context);
this.handleFiles = this.handleFiles.bind(this);
this.prepareTable = this.prepareTable.bind(this);
this.state = {excel: null};
}
render() {
const {location, push, goBack} = this.props.routing;
const {userStore} = this.props.userStore;
And in index.js i do
const stores = {
// Key can be whatever you want
routing: routingStore,
UserStores
};
const history = syncHistoryWithStore(browserHistory, routingStore);
ReactDOM.render(
<Provider {...stores}>
<Router history={history}>
<Entry/>
</Router>
</Provider>,
document.getElementById('root')
);
Lets, after all of this i try open the localhost:3000 and se this error
Error: MobX observer: Store 'UserStore' is not available! Make sure it is provided by some Provider
UPDATE:
I'm create a project with create-react-app, and i can't use # in code(example for #injector)
I think you should return an instance of the store.
To be a bit more organized I have a file like "storeInitializer.ts" (using typescript here):
import YourStoreName from '../yourStoreFolder/yourStore';
export default function initializeStores() {
return {
yourStoreName: new YourStoreName(),
}
}
Then I have another file like "storeIdentifier.ts":
export default class Stores {
static YourStoreName: string = 'yourStoreName';
}
In the app file I do something like this:
import React from 'react';
import { inject, observer } from 'mobx-react';
import Stores from './storeIdentifier';
const App = inject(Stores.YourStoreName)(observer(props: any) => {
//code here
});
export default App;
or if you are using the class component approach...
import React from 'react';
import { inject, observer } from 'mobx-react';
#inject(Stores.YourStoreName)
#observable
class App extends Component {
//code here
}
export default App;
I'm learning redux and react. I am following some tutorials, in order to make a app.
I have this action:
export function getDueDates(){
return {
type: 'getDueDate',
todo
}
}
this is the store:
import { createStore } from 'redux';
import duedates from './reducers/duedates'
export default createStore(duedates)
This is the reducer:
import Immutable from 'immutable'
export default (state = Immutable.List(['Code More!']), action) => {
switch(action.type) {
case 'getDueDate':
return state.unshift(action.todo)
default:
return state
}
}
and in the entry point js I have this:
import React from 'react';
import ReactDOM from 'react-dom';
import store from './app/store'
import { Provider } from 'react-redux'
import App from './app/Components/AppComponent';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
Now, (according to some examples), I should call getDueDate from the dispatch but I dont get how to get the dispatch on the component, to trigger the action
Use connect from react-redux package. It has two functions as params, mapStateToProps and mapDispatchToProps, which you are interested in now. As per answer from Nick Ball, which is partially right, you will be exporting like this:
export default connect(mapStateToProps, mapDispatchToProps)(App)
and your mapDispatchToProps will look something like this:
function mapDispatchToProps (dispatch, ownProps) {
return {
getDueDate: dispatch(getDueDate(ownProps.id))
}
}
as long as your component connected to the store has property id passed from above, you'll be able to call this.props.getDueDate() from inside of it.
EDIT: There is probably no need of using an id in this case, however my point was to point out that props go as second parameter :)
The missing piece here is the connect function from react-redux. This function will "connect" your component to the store, giving it the dispatch method. There are variations on how exactly to do this, so I suggest reading the documentation, but a simple way would be something like this:
// app/Components/AppComponent.js
import { connect } from 'react-redux';
export class App extends React.Component {
/* ...you regular class stuff */
render() {
// todos are available as props here from the `mapStateToProps`
const { todos, dispatch } = this.props;
return <div> /* ... */ </div>;
}
}
function mapStateToProps(state) {
return {
todos: state.todos
};
}
// The default export is now the "connected" component
// You'll be provided the dispatch method as a prop
export default connect(mapStateToProps)(App);
I'm trying to write unit tests for a container component called AsyncApp but I get the following error "mapStateToProps must return an object. Instead received undefined."
This is my set-up.
Root.js
import configureStore from '../configureStore';
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import AsyncApp from './AsyncApp';
const store = configureStore();
export default class Root extends Component {
render() {
return (
<Provider store={store}>
<AsyncApp />
</Provider>
);
}
}
configureStore.js
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import rootReducer from './reducers';
const loggerMiddleware = createLogger();
const createStoreWithMiddleware = applyMiddleware(
thunkMiddleware
//loggerMiddleware
)(createStore);
export default function configureStore(initialState) {
return createStoreWithMiddleware(rootReducer, initialState);
}
AsyncApp.js
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { foo } from '../actions';
import FooComponent from '../components/FooComponent';
class AsyncApp extends Component {
constructor(props) {
super(props);
this.onFoo= this.onFoo.bind(this);
this.state = {}; // <--- adding this doesn't fix the issue
}
onFoo(count) {
this.props.dispatch(foo(count));
}
render () {
const {total} = this.props;
return (
<div>
<FooComponent onFoo={this.onFoo} total={total}/>
</div>
);
}
}
function mapStateToProps(state) {
return state;
}
export default connect(mapStateToProps)(AsyncApp);
I'm passing store directly to AsyncApp in my test to avoid getting the following Runtime Error : Could not find "store" in either the context or props of "Connect(AsyncApp)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(AsyncApp)".
The test isn't complete yet because I can't get past the mapStateToProps error message.
AsyncApp-test.js
jest.dontMock('../../containers/AsyncApp');
jest.dontMock('redux');
jest.dontMock('react-redux');
jest.dontMock('redux-thunk');
jest.dontMock('../../configureStore');
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
const configureStore = require( '../../configureStore');
const AsyncApp = require('../../containers/AsyncApp');
const store = configureStore();
//const asyncApp = TestUtils.renderIntoDocument(
//<AsyncApp store={store} />
//);
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(<AsyncApp store={store}/>);
I want to eventually test that AsyncApp contains a FooComponent, and that a foo action is dispatched when onFoo is called.
Is what I am trying to do achievable? Am I going about this the right way?
The suggestion I've seen in a few places is to test the non-connected component, as opposed to the connected version. So, verify that when you pass in specific props to your component you get the expected rendered output, and verify that when you pass in a state with a certain shape your mapStateToProps() returns the expected pieces. Then you can expect that they should both work correctly when put together.