I want to make my main component state aware without creating additional files, if possible... Here's my code:
import React from 'react';
import { Provider } from 'react-redux';
import { connect } from 'react-redux';
import store from './store';
const App = ({ isAuthenticated }) => {
return (
<Provider store={store}>
{isAuthenticated ? (
<>
<p>...AUTHED...</p>
</>
) : (
<>
<p>...NOT AUTHED...</p>
</>
)}
</Provider>
);
};
const mapStateToProps = state => ({
isAuthenticated: state.mode.isAuthenticated
});
export default connect(mapStateToProps)(App);
I get error : "Could not find "store" in the context of "Connect(App)". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(App) in connect options."
I tried changing my code, but it didn't work
import React from 'react';
import { Provider } from 'react-redux';
import { connect } from 'react-redux';
import store from './store';
const AppWithStore = () => {
return (
<Provider store={store}>
<App />
</Provider>
);
};
const App = ({ isAuthenticated }) => {
return (
<>
{isAuthenticated ? (
<>
<p>...AUTHED...</p>
</>
) : (
<>
<p>...NOT AUTHED...</p>
</>
)}
</>
);
};
const mapStateToProps = state => ({
isAuthenticated: state.mode.isAuthenticated
});
export default connect(mapStateToProps)(AppWithStore);
Am I missing something ?
The Provider "makes the redux store available to any nested components." - https://react-redux.js.org/api/provider#overview
You don't want to "connect" your component with the Provider (AppWithStore), you want to "connect" any children of Provider (App)
Based on your second example:
You need to connect your App component, not AppWithStore
connect(mapStateToProps)(App);
Then be sure you're default exporting AppWithStore
import React from 'react';
import { Provider } from 'react-redux';
import { connect } from 'react-redux';
import store from './store';
let App = ({ isAuthenticated }) => {
return (
<>
{isAuthenticated ? (
<>
<p>...AUTHED...</p>
</>
) : (
<>
<p>...NOT AUTHED...</p>
</>
)}
</>
);
};
const mapStateToProps = state => ({
isAuthenticated: state.mode.isAuthenticated
});
App = connect(mapStateToProps)(App);
const AppWithStore = () => {
return (
<Provider store={store}>
<App />
</Provider>
);
};
export default AppWithStore;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With