Error in react-native with expo: Could not find "store" in the context of "Connect(App)" - react-native

I'm building my first react native app and I encountered a problem to connect to redux store (I also do not have much experience with redux yet). I am using expo.
The error is:
Invariant Violation: 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.
This error is located at:
in Connect(App) (at withExpoRoot.js:22)
(...)
Here is my code:
Could you please help?
// App.js
import React, { Component } from "react";
import AppStackNav from "./navigators/AppStackNav";
import { Provider, connect } from 'react-redux';
import { createStore } from 'redux';
import guestsReducer from "./reducers/GuestsReducer";
const store = createStore(guestsReducer);
class App extends Component {
constructor(props) {
super(props);
}
addGuest = (index) => {
// ...
}
render() {
return (
<Provider store={store}>
<AppStackNav
screenProps={{
currentGuests: this.state.currentGuests,
possibleGuests: this.state.possibleGuests,
addGuest: this.addGuest
}}
/>
</Provider>
)
}
}
const mapStateToProps = state => {
return {
currentGuests: this.state.current,
possibleGuests: this.state.possible,
addGuest: this.addGuest
};
}
export default connect(mapStateToProps)(App);
// GuestsReducer.js
import { combineReducers } from 'redux';
const INITIAL_STATE = {
current: 10,
possible: [
'Guest1',
'Guest2',
'Guest3',
'Guest4',
],
};
const guestsReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
default:
return state
}
};
export default combineReducers({
guests: guestsReducer,
});
// AppStackNav.js
import { createStackNavigator, createAppContainer } from "react-navigation";
import Home from "../screens/Home";
import Dashboard from "../screens/Dashboard";
import Project from "../screens/Project";
import Placeholder from "../screens/Placeholder";
const AppStackNav = createStackNavigator({
// ...
});
export default createAppContainer(AppStackNav);

First Issue
const mapStateToProps = ({ guests }) => {
return {
currentGuests: guests.current,
possibleGuests: guests.possible
};
}
Second Issue
You wire redux store to your upper level component which is the App component ... and then use connect and mapStateToProps to access redux store in the children of this upper level component (App) ... I mean you connect your store via mapStateToProps to your AppStackNav component not the App component
const AppStackNav = ({ currentGuests, possibleGuests }) => {
const Stack = createStackNavigator({...});
return <Stack />;
};
const mapStateToProps = ({ guests }) => {
return {
currentGuests: guests.current,
possibleGuests: guests.possible
};
}
// react-navigation v2 is needed for this to work:
export default connect(mapStateToProps)(AppStackNav);
App.js
class App extends Component {
constructor(props) {
super(props);
}
addGuest = (index) => {
// ...
}
render() {
return (
<Provider store={store}>
<AppStackNav />
</Provider>
)
}
}
export default App;

you can't use 'this' keyword outside the class as It wont be able to understand the context for that particular method.
you need to simply remove this keyword from mapStateToProps
like this:
const mapStateToProps = state => {
return {
currentGuests: state.current,
possibleGuests: state.possible
};
}

Related

How to test a custom react hook which uses useNavigation from 'react-navigation-hooks' using Jest?

I have a custom react hook 'useSample' which uses useNavigation and useNavigationParam
import { useContext } from 'react'
import { useNavigation, useNavigationParam } from 'react-navigation-hooks'
import sampleContext from '../sampleContext'
import LoadingStateContext from '../LoadingState/Context'
const useSample = () => {
const sample = useContext(sampleContext)
const loading = useContext(LoadingStateContext)
const navigation = useNavigation()
const Mode = !!useNavigationParam('Mode')
const getSample = () => {
if (Mode) {
return sample.selectors.getSample(SAMPLE_ID)
}
const id = useNavigationParam('sample')
sample.selectors.getSample(id)
navigation.navigate(SAMPLE_MODE_ROUTE, { ...navigation.state.params}) // using navigation hook here
}
return { getSample }
}
export default useSample
I need to write unit tests for the above hook using jest and I tried the following
import { renderHook } from '#testing-library/react-hooks'
import sampleContext from '../../sampleContext'
import useSample from '../useSample'
describe('useSample', () => {
it('return sample data', () => {
const getSample = jest.fn()
const sampleContextValue = ({
selectors: {
getSample
}
})
const wrapper = ({ children }) => (
<sampleContext.Provider value={sampleContextValue}>
{children}
</sampleContext.Provider>
)
renderHook(() => useSample(), { wrapper })
})
})
I got the error
'react-navigation hooks require a navigation context but it couldn't be found. Make sure you didn't forget to create and render the react-navigation app container. If you need to access an optional navigation object, you can useContext(NavigationContext), which may return'
Any help would be appreciated!
versions I am using
"react-navigation-hooks": "^1.1.0"
"#testing-library/react-hooks":"^3.4.1"
"react": "^16.11.0"
You have to mock the react-navigation-hooks module.
In your test:
import { useNavigation, useNavigationParam } from 'react-navigation-hooks';
jest.mock('react-navigation-hooks');
And it's up to you to add a custom implementation to the mock. If you want to do that you can check how to mock functions on jest documentation.
for me, soved it by usingenter code here useRoute():
For functional component:
import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '#react-navigation/native';
function MyBackButton() {
const navigation = useNavigation();
return (
<Button
title="Back"
onPress={() => {
navigation.goBack();
}}
/>
);
}
For class component:
class MyText extends React.Component {
render() {
// Get it from props
const { route } = this.props;
}
}
// Wrap and export
export default function(props) {
const route = useRoute();
return <MyText {...props} route={route} />;
}

Redux & React Native component connect: this.props is undefined

I am trying to access the name field as defined in the initial state of my reducer. At the moment, this.props is returning undefined.
My reducer:
import { combineReducers } from 'redux';
const INITIAL_STATE = {
name: "Test"
}
const userReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
default:
return state
}
};
export default combineReducers({
user: userReducer,
});
The component being rendered (this logs "Props: undefined"):
const AddName = ({ navigation }) => {
...
console.log("Props: ", this.props)
return (
<>
...
</>
)
}
mapStateToProps = (state) => {
return{
user : state.user
};
}
export default connect(mapStateToProps, null)(AddName)
Creating the redux store and provider:
...
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from './src/reducers/userReducer';
const store = createStore(reducer)
const AppContainer = () =>
<Provider store={store} >
<App />
</Provider>
AppRegistry.registerComponent(appName, () => AppContainer);
You are using a functional component and this keyword doesnt apply to functional components, rather it applies it to class Components.
Change your component as below :
class AddName extends React.Component {
...
console.log("Props: ", this.props)
render(){
return (
<>
...
</>
)
}
}
mapStateToProps = (state) => {
return{
user : state.user
};
}
export default connect(mapStateToProps, null)(AddName)
hopeit helps. feel free for doubts
You are using a function Component so you should use props in this way :
const AddName = (props) => {
...
console.log("Props: ", props)
return (
<>
...
</>
)
}
You should use class components instead of the function component.
Read more about that.
https://codeburst.io/react-js-understanding-functional-class-components-e65d723e909

Invariant Violation: Could not find “store” React Native

I get the following error using redux in native react
Invariant Violation: Invariant Violation: Could not find "store" in
the context of "Connect(Lista)". Either wrap the root component in a
, or pass a custom React context provider to and
the corresponding React context consumer to Connect(Lista) in connect
options.
My code is the following
SettingStore
import {createStore, applyMiddleware} from 'redux';
import Reducers from './Reducer'
import thunk from 'redux-thunk'
export default SettingStore = () => {
let store = createStore(Reducers, applyMiddleware(thunk))
return store
}
my index reducer
import {combineReducers} from 'redux';
import loginreducer from './login.reducer'
export default combineReducers({
login: loginreducer,
})
my index action
import {FETCHING_GETDATA_PARVU} from '../Constante'
import {GetParv} from '../Api/Parvularia.api'
export const getParvuSuccess = (data) => {
return {type: FETCHING_GETDATA_PARVU, data}
}
export const GetParvu = () => {
return (dispatch) => {
dispatch(getData())
GetParv(1)
.then(([response, json]) => {
dispatch(getParvuSuccess(json))
})
.catch((error) => console.log(error))
}
}
This is the maintab.reducer of my reducer
import {FETCHING_GETDATA_PARVU} from '../Constante'
const initialState = {
data: [],
isFeching: false,
error: false
}
export default dataReducer = (state = initialState, action) => {
switch(action.type) {
case FETCHING_GETDATA_PARVU:
return {
...state,
data: action.data,
isFeching: false
}
default:
return state
}
}
and let's say this is my app.js of the redux structure
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import {Provider} from 'react-redux';
import Lista from '../screens/Educadora/Lista';
import SettingStore from './SettingStore'
let store = SettingStore()
const Ap = () => (
<Provider store={store}>
<Lista/>
</Provider>
)
export default Ap;
This last part is the one that generates me more doubt, I think that this is my error but I do not know why I am new in react native
Edit
This is where I want to show the query made with redux
import { connect } from 'react-redux'
import {GetParvu} from '../../Redux/Actions'
class Lista extends React.Component {
componentWillMount() {
this.props.GetParvu()
render(){
return(algoaca)
}
}
}
const mapStateToProps = state => {
return {
parvu: state.data
}
}
const mapDispatchToProps = dispatch => {
return {
GetParvu: () => {
return dispatch(GetParvu(1))
}
}
}
AppRegistry.registerComponent('EqualsMobile', () => Lista);
export default connect(mapStateToProps, mapDispatchToProps)(Lista);
You have connecting your component in wrong way. connect() is high order component that take mapStateToProps as an argument to map store to your component.
You can use it in your component like this.
function mapStateToProps(state){
return {state}
}
export default connect(mapStateToProps)(your_component_name);

Redux : problem with the store to exchange data

I want to test Redux on my react-native app. I navigate through several Components - I want a component TestRedux updates a value and that another component TestRedux2 see this value using Redux.
I followed several tutorials on Redux and did this:
Actions:
//myApp/redux/Actions/action.js
import { ADD_RES } from "../Constants/action-types";
export function addResa(payload) {
return { type: ADD_RES, payload: payload };
}
Constants:
//myApp/redux/Components/action-types.js
export const ADD_RES = "ADD_RES";
export const DEL_RES = "DEL_RES";
Reducers:
//myApp/redux/Reducers/resaReducer.js
import { ADD_RES } from "../Constants/action-types";
const initialState = {
res: []
};
function resaReducer(state = initialState, action) {
let nextState;
switch (action.type) {
case ADD_RES:
nextState = {
...state,
payload: action.payload
}
return nextState;
default:
return state
}
}
export default resaReducer;
Store:
//myApp/redux/Store/store.js
import { createStore } from "redux";
import resaReducer from "../Reducers/resaReducer";
const Store = createStore(resaReducer);
export default Store;
TestRedux:
//myApp/redux/Components/TestRedux.js
// I use react-navigation to navigate between components. The component App is the first component and then trigger to testRedux
import React from 'react';
import { View, Text, Alert } from 'react-native';
import { ADD_RES } from "../Constants/action-types";
import {addResa} from "../Actions/actions";
import { connect } from 'react-redux'
import { Provider } from 'react-redux'
import Store from '../Store/store'
import App from '../../App';
const mapStateToProps = (state) => {
return state.date
}
export class TestRedux extends React.Component {
render() {
this.props.dispatch(addResa(2));
return (
<View>
<Button
onPress={() => {this.props.navigation.navigate('TestRedux2')}}
title='test'
/>
<Provider store={Store}>
<App/>
</Provider>
</View>
)
}
}
export default connect(mapStateToProps)(TestRedux)
TestRedux2:
//myApp/redux/Components/TestRedux2.js
import { connect } from 'react-redux'
import React from 'react';
import { View, Text, Button, Alert } from 'react-native';
import { ADD_RES } from "../Constants/action-types";
import {addResa} from "../Actions/actions";
import Store from '../Store/store'
const mapStateToProps = (state) => {
return state.date
}
export class TestRedux2 extends React.Component {
render() {
console.log("Value from TestRedux2 is", Store.getState())
return (
<View>
<Text> Hello </Text>
</View>
)
}
}
export default connect(mapStateToProps)(TestRedux2)
Do I use correctly Redux ?
I have the following error: “Invariant Violation: Could not find "store" in the context of "Connect(TestRedux)". Either wrap the root component in a , or pass a custom React context provider to and the corresponding React context consumer to Connect(TestRedux) in connect options.”
This code:
<Provider store={Store}>
<App/>
</Provider>
which is inside your TestRedux, should be inside your index.js file as follows:
render(
<Provider store={Store}>
<App/>
</Provider>,
document.getElementById('root')
)
import of course your store. That is assuming you haven't made any other changes in your initial index.js file.

redux state don't send when use react-navigation

i am using react-navigation and redux in react-native.when i just used redux, the states can send to child by redux. but it don't work when i add react-navigation.
my navigation.js
import {StackNavigator} from 'react-navigation';
import Home from './modules/home/views/Home'
export const StackRouter = StackNavigator({
Main: {screen: Home},
initialRouteName: {screen: Home}
});
const firstAction = StackRouter.router.getActionForPathAndParams('Main');
const tempNavState = StackRouter.router.getStateForAction(firstAction);
const initialNavState = StackRouter.router.getStateForAction(
firstAction,
tempNavState
);
//navigationreducer
export const stackReducer = (state=initialNavState,action) => {
debugger
const newState = StackRouter.router.getStateForAction(action, state);
return newState || state;
};
my store.js
import React, {Component} from 'react';
import { connect, Provider } from 'react-redux';
import {createStore, combineReducers, bindActionCreators, applyMiddleware } from 'redux';
import {addNavigationHelpers} from 'react-navigation'
import thunk from 'redux-thunk'
import PropTypes from 'prop-types'
import {StackRouter, stackReducer} from './router'
import home from './modules/home';
//routerConmponent
class RouterAppWithState extends Component {
constructor(props){
super(props)
}
render() {
return (
<StackRouter navigation={addNavigationHelpers({
dispatch: this.props.dispatch,
state: this.props.router,
})} />
);
}
}
//all reducer
const reducer = combineReducers({
home: home.reducer,
router: stackReducer,
});
const mapActionToProps = (dispatch) => {
return {
home_actions: bindActionCreators(home.actions, dispatch)
}
};
const mapStateToProps = (state) => {
debugger;
return state
};
//connect redux and navigation
const StoreApp = connect(mapStateToProps, mapActionToProps)(RouterAppWithState);
const store = applyMiddleware(thunk)(createStore)(reducer);
export default class RootApp extends Component{
render() {
return(
<Provider store={store}>
<StoreApp />
</Provider>
)
}
}
my home.js ,just import actions and reducers, and export the module
import actions from './store/actions';
import reducer from './store/reducer'
export default {
actions,
reducer
}
my reducers
export default(state=states, action) => {
let newState = {...state};
switch (action.type){
case TYPES.ADD_COUNT: newState.count = state.count+1;break;
default: break;
}
return newState
};
my actions
const add_count = () => {
console.log('add');
return async (dispatch) => {
dispatch({type: TYPES.ADD_COUNT});
await new Promise((resolve) => {setTimeout(() => {resolve()} , 3000)});
dispatch({type: TYPES.ADD_COUNT});
};
};
export default {
add_count
}
my view Home.js
import React, {Component, StyleSheet} from 'react';
import {View, Text, Button} from 'react-native';
export default class Home extends Component{
constructor(props){
super(props)
}
// static contextTypes = {
// navigation: React.PropTypes.Object
// };
render() {
debugger
const {add_count} = this.props.home_actions;
const {count} = this.props.home;
return (
<View>
<Text >{count}</Text>
<Button onPress={add_count} title={'add count'}/>
{/*<Button onPress={() => {navigation.navigate('live')}} title={'live'}/>*/}
</View>
)
}
}
In Home.js function render, this.props is
{
navigation: Object,
screenProps: undefined
}
has not states in redux. but without react-navigation, this.props is
{
home: Object,
home_actions: Object
}
thanks
The reason is because now the StackRouter is controlling the rendering of your Home page. The router only pass down a prop called navigation and whatever you pass down from screenProps.
There are two ways that you can achieve a similar behavior as before:
1) In RouterAppWithState's render function, pass down this.props into screenProps like this
<StackRouter navigation={addNavigationHelpers({
dispatch: this.props.dispatch,
state: this.props.router,
})}
screenProps={this.props}
/>
2) (recommended) The other way is to directly use connect on your home page to connect your Home component to the store and access home specific part of the store. i.e. connect(mapStateToProps)(Home)