I'm trying to upgrade to Redux V6 but am confused on how to use the createContext function and it's necessity. I know my store is created successfully, but when I try to run my app I get
Could not find "store" in the context of "Connect(ConfiguredApp)".
Either wrap the root component in a , or pass a custom React
context provider to and the corresponding React context
consumer to Connect(ConfiguredApp) in connect options.
Which tells me that my provider is not properly passing down the store for connect to grab. What am I doing wrong? Thanks!
import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import {ConnectedRouter} from 'connected-react-router';
import {history, store} from './store/store';
import Routes from './routes';
const customContext = React.createContext(null);
render(
<Provider store={store} context={customContext}>
<ConnectedRouter history={history} context={customContext}>
<Routes />
</ConnectedRouter>
</Provider>, document.getElementById('app'),
);
You almost definitely shouldn't be creating and passing in a custom context instance. That's only if, for some very specific reason, you want to use a context instance other than the default one that React-Redux already uses internally. (A hypothetical reason to do this would be if you are using one store for your whole app component tree, but there's a specific subtree that needs to receive data from a different store instead.)
If you actually wanted to use your own custom context instance, then you would need to pass the same context instance to both <Provider> and each connected component in the app that needs to receive data from that <Provider>.
Looking at the connected-react-router docs, they do claim that in CRR version 6, you can pass a context instance to <ConnectedRouter>, but that shouldn't be necessary here.
More specifically, if you look at the error message, it says the problem is in Connect(ConfiguredApp). So, it's your own connected component that is saying there's a context mismatch.
Ultimately, the answer here is to delete the context arguments from both <Provider> and <ConnectedRouter>. You don't need them.
Related
I am confused about why a create-react-app has both
import {store} from './our-redux-store'
const app = () => {
return (
<Provider store={store}>
<WholeAppGoesHere/>
</Provider>
)
}
versus using connect with a component like so:
import {connect} from 'react-redux';
class MyComp {
// ...
}
export default connect(
mapState,
mapDispatch
)(MyComponent);
do we need both? what's the difference?
The provider is a component. You use the provider at the top of the component chain where your application starts. You place it so it wraps your entire application. Within this container, you pass the store. This allows any child component to access the store.
connect() is used as a higher-order function that you wrap around specific components. Connect in essence maps state data contained within the store to the props within that specific component. Maybe it helps to think of connect() as a way an individual component gets the specific data it needs from the global store
Provider is a part of React Context functionality. By assigning your store there, it makes the specific value of store available to all consumers of that context.
connect() on the otherhand is a higher order component that injects your mapped states and dispatches into the props of your base component. To do so, it calls the Consumer part of this api to access the store context.
Edit: https://react-redux.js.org/using-react-redux/accessing-store#understanding-context-usage
What is the best pattern for a large multi-component ReactJS app to integrate with a socket io back-end server?
Here are some of the requirements
The React application must connect to the backend (a server using a Flask-based socket.io implementation) upon login. The connection must be torn down on logout
The connection should be managed from a central place (as in I don't want every component to connect/disconnect to socket-io). This should also be a place to manage life-cycle of the socketio connection (disconnect, reconnect, etc).
Back-end will send async updates (a.k.a statistics for various components). These stats must be handled by the common socketio handling instance and pushed into redux store. The message body will have enough information to demux the messages.
The components themselves, should (preferably) not know about socket-io, they operate on the redux state.
Components can dispatch actions, that could potentially result in sending out a socketio message (to back-end).
[I don't have a use-case where a client needs to talk to another client.]
Few questions:
What is the right way to design this? At what point should I connect to socket-io?
I have a basic-layout component which is used by all pages. Is this the right place to hook up socket-io call? However, I see that this component is unloaded/loaded for each page. Somehow, this doesn't feel like the right place
I have seen some examples where every page opens a socketio connection. I am not sure if this is the right model?
I think you should probably store your socket on a Context, so that you can create your socket on your index.js file, like I did here :
import React from "react";
import App from "./App";
import socketIOClient from "socket.io-client";
import { MainProvider } from "./context/MainContext.js";
const ENDPOINT = "http://127.0.0.1:1234"; //Your backend endpoint
ReactDOM.render(
<React.StrictMode>
<MainProvider value={{socket: socketIOClient(ENDPOINT)}}>
<App />
</MainProvider>
</React.StrictMode>,
document.getElementById("root")
);
Then as it is on the context, you can access it in any component, like that :
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import MainContext from "./context/MainContext"; //import your context here
const myComponent = props => {
const myContext = useContext(MainContext); //your context is stored in a prop
return (
<div></div>
);
};
myComponent.propTypes = {
};
export default myComponent;
Finally you can access your socket in the component by calling myContext.socket
We are building a Storybook UI library from our existing code base. The code wasn't written with component driven development in mind. There are many instances where a component renders descendants that are connected to the Redux store.
E.g., Parent (connected) -> Child (unconnected) -> Grandchild (connected)
Now if I'm building a story for Parent, I understand how to pass hard-coded data as a prop to an immediate child component in order to avoid Redux all together. However, I can't figure out how to do this when the connected component is more deeply nested.
Ideally I don't want to have to use Redux at all for stories, but even if I do initialize a Redux store and wrap the parent component in a Provider as described here, would this even work to connect the grandchild component?
Any ideas would be helpful.
When using storybook you can add a Decorator for all stories (see link for most updated API).
It is common to wrap your stories with the state manager store provider in order to not break the story avoiding "adding a store for each story".
// # config.js
import { configure, addDecorator } from '#storybook/react';
import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from 'reducers/root.reducer';
const store = createStore(rootReducer);
addDecorator(S => (
<Provider store={store}>
<S />
</Provider>
));
configure(require.context('../src', true, /\.stories\.js$/), module);
Note that you can avoid connecting all your components with redux-hooks which in addition removes all the boilerplate code of redux.
React Redux now offers a set of hook APIs as an alternative to the existing connect() Higher Order Component. These APIs allow you to subscribe to the Redux store and dispatch actions, without having to wrap your components in connect().
If you want to solve the problem within your story file (and just fetch your store), use decorator like this:
import React from "react";
import { Provider } from 'react-redux'
import Parent from "./Parent";
import { store } from "../../../redux/store";
export default = {
title: "pages/Parent",
component: Parent,
decorators : [
(Story) => (<Provider store={store}><Story/></Provider>)
]
};
Sidenote, if this gives you the error useNavigate() may be used only in the context of a <Router> component., then you may need <MemoryRouter><Provider store={store}><Story/></Provider></MemoryRouter> (import {MemoryRouter} from 'react-router-dom')
The best practice for using Redux in React application is wrapping the component in a 'Provider' component:
const rootElement = document.getElementById('root')
ReactDOM.render(
<Provider store={store}>
<TodoApp />
</Provider>,
rootElement
)
You can see it in React-Redux documentation: https://react-redux.js.org/introduction/basic-tutorial.
What is the benefit we get from this attitude?
Why not just importing the 'store' inside the 'ToDoApp' component and access 'store' as an imported variable? For example:
import { store } from './store';
class TodoApp extends Component {
constructor(props) {
super(props);
console.log('constructor')
}
render() {
console.log(store.getState());
}
}
The actual point that is happening in the redux, when we are calling the provider: that it is having the store of all the states and the provider does the job to connect the component with the redux or simply you can say that the provider does the job to connect your app with the redux as the author of the redux has not only to design the library for a single framework, it would have so many uses on different platforms, the store is having two things inside (reducers and state) and all the states get an outer layer of provider which connects the app with the redux library.
This is very important to the way react-redux works.
When you use connect over your component, it attempts to get the store from the Provider you set, using React's context mechanism.
It is highly unlikely that you will use Redux in React without using connect, so I would advise that you keep it there.
Is it possible to ES6 import a React component from node_modules that depends on a Context Provider (like react-redux 6.0) without the Provider Context being exported by that module?
For example, the implementation of the import would wrap the imported component with its own Provider.
import App from 'app-package'
import { Provider } from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('example'),
);
this works in react-redux 5.1.1 but not in 6.0.0, I assume because 6.0.0 is now using the React Context API. The problem may also be webpack related.
Found this https://github.com/facebook/react/issues/13336.
It seems that <App/> must have its own Provider Context since it is outside of the imperative boundary.
To share store with <App/>, one can use ReactReduxContext.Consumer and pass store as a prop to it (via a component wrapper)