I am trying to pass in store as a property to AddTodo but I am getting the error: Cannot read property 'todos' of undefined
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { connect } from 'react-redux'
import { createStore } from 'redux'
const todo = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text
}
default:
return state
}
}
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
];
default:
return state
}
}
let store = createStore(todos)
let nextTodoId = 0
const AddTodo = () => {
let input;
//this works
console.log(store.getState())
//this doesn't
console.log(this.props.todos)
return (
<div>
<input ref={node => {input = node}}/>
<button onClick = {() => {
store.dispatch({
type: 'ADD_TODO',
id: nextTodoId++,
text: input.value
});
input.value = ''
}}>
Add Todo
</button>
</div>
)
};
store.subscribe(AddTodo)
ReactDOM.render(
<AddTodo
todos={store.getState()}
/>,
document.getElementById('root'));
I am a little confused why I am getting the error when printing this.props.todos. I thought I was passing in todos as a prop in <AddTodo todos={...}/>
Functional components work differently, they don't have a context of this, but their props are passed through the arguments of the function
To make it work, just change your function call of addToDos, like this:
const AddTodo = (props) => {
let input;
console.log(props.todos);
return (/* and the rest of your code...*/) ;
};
For the rest, as Arun Ghosh is saying, you should revisit your subscribe pattern, for example like this
store.subscribe(() => {
ReactDOM.render(
<AddTodo
todos={store.getState()}
/>,
document.getElementById('root'));
});
You should pass the store object and subscribe for changes
store.subscribe(() => {
// In our case the state will be updated when todos are set
console.log(store.getState().todos);
});
Related
I am creating an app with reactjs and I am using context api as my state management tool
but the dispatch does not dispatch the values
city shows undefined even after the dispatch has been called.
SearchContext
Here I created the initial state where the city is undefined, date is an empty array and option values are undefined on the initial state
I just have two actions search and reset action which should be dispatched when the user click on a button
import { useReducer } from "react"
import { createContext } from "react"
const INITIAL_STATE = {
city: undefined,
dates: [],
options: {
adult: undefined,
children: undefined,
room: undefined,
}
}
export const SearchContext = createContext(INITIAL_STATE)
const SearchReducer = (state, action) => {
switch (action) {
case "NEW_SEARCH":
return action.payload;
case "RESET_SEARCH":
return INITIAL_STATE;
default:
return state
}
}
export const SearchContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(SearchReducer, INITIAL_STATE)
return (
<SearchContext.Provider
value={{ city: state.city, dates: state.dates, options: state.options, dispatch }}>
{children}
</SearchContext.Provider>
)
}
index.js
I wrapped the whole app with my searchcontext provider so that I can access the values that is passed down to all the components
import App from './App';
import { SearchContextProvider } from './context/SearchContext';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<SearchContextProvider>
<App />
</SearchContextProvider>
</React.StrictMode>
);
header.js
import { useContext } from "react";
import { SearchContext } from "../../context/SearchContext";
const Header = () => {
const { dispatch } = useContext(SearchContext)
const handleSearch = (e, dispatch) => {
dispatch({ type: "NEW_SEARCH", payload: { destination, "dates": "14-may-2122", options } })
navigate("/hotels", { state: { destination, dates, options } });
};
return (
<div className="header">
<button className="headerBtn" onClick={(e) => handleSearch(e, dispatch)}>
Search
</button>
</div>
)
}
You forgot .type
const SearchReducer = (state, action) => {
switch (action.type) { // <--- add `.type` here
case "NEW_SEARCH":
return action.payload;
case "RESET_SEARCH":
return INITIAL_STATE;
default:
return state
}
}
I have a React app with a currency unit switch. I have a function to switch the unit and update redux so that every component that has called the unit will be re-rendered. The problem is the redux prop (storedCurrencyUnit) is UNDEFINED whenever I updated the value and call the update function to redux.
Switch component
import { compose } from 'recompose';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { updateCurrencyUnit } from '../../store/actions';
class FrontHeader extends Component {
handleCurrencyChange = (e) => {
const { updateCurrencyUnit, storedCurrencyUnit } = this.props;
updateCurrencyUnit(e.target.checked)
console.log("unit", storedCurrencyUnit) // this is UNDEFINED
this.setState({ aud: e.target.checked }, () => {
localStorage.setItem("currencyUnit", this.state.aud ? "AUD" : "USD")
})
}
render() {
return (
<Switch
checked={this.state.aud}
onChange={this.handleCurrencyChange}
color="secondary"
name="aud"
inputProps={{ 'aria-label': 'currencyUnit' }}
/>
)
}
}
const mapStateToProps = (state) => ({
storedCurrencyUnit: state.storedCurrencyUnit
})
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
updateCurrencyUnit: updateCurrencyUnit,
}, dispatch);
}
export default compose(connect(mapStateToProps, mapDispatchToProps))(FrontHeader);
currencyReducer.js
const storedCurrencyUnit = (state = null, action) => {
switch (action.type) {
case 'UPDATE_CURRENCYUNIT':
return action.payload;
default:
return state;
}
}
export default storedCurrencyUnit;
actions.js
export const updateCurrencyUnit = (updatedCurrencyUnit) => {
return {
type: 'UPDATE_CURRENCYUNIT',
payload: updatedCurrencyUnit,
}
}
How can I solve this?
You need to dispatch the action using dispatcher. only that will maintain the promise and let know the redux store.
this.props.dispatch(updateCurrencyUnit("some value"));
I am using React redux with firebase realtime database.
In App.js I am dispatching an action fetchAllPosts
App.js
class App extends Component {
componentDidMount() {
this.props.fetchAllPosts();
}
render() {
return (
<div className="App">
// something ...
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
fetchAllPosts: () => {dispatch(allPosts())}
}
}
My action looks like this (I am using redux-thunk):
action
export function allPosts() {
return (dispatch) => {
firebase.database().ref('posts/').on('value', (snapshot) => {
dispatch({type: "ALL_POSTS", postsArray: snapshot.val(), loading: false})
})
}
}
Then I am combining reducers (I know in this case it is not necessary):
const rootReducer = combineReducers({
allPosts: postsReducer
})
My reducer looks like this:
reducer
const initialState = {
allPosts: []
}
const postsReducer = (state = initialState, action) => {
switch(action.type) {
case "ALL_POSTS" :
console.log("action payload all posts", action.postsArray)
return {
...state,
loading: false,
allPosts: action.postsArray
}
break;
default:
return state
}
return state
}
And finally: my SinglePostview component looks like this:
SinglePostview.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
class SinglePostview extends Component {
render() {
console.log("ppp", this.props)
return (
<h2>{this.props.post.title}</h2>
)
}
}
const mapStateToProps = (state, ownprops) => {
const postId = ownprops.match.params.postid
return {
post: state.allPosts.allPosts[postId]
}
}
export default connect(mapStateToProps)(SinglePostview);
Here when the render method is executing, this.props.post is undefined and I have the error:
TypeError: Cannot read property 'title' of undefined.
The problem is: when the app loads for the first time, props.post is undefined (so I have an error) and after about 1 second it receives the value but it doesn't change anything - the error still exists and the value is not displaying.
Could anyone help me?
Assuming your reducer is fine, you can fix this by
changing this
render() {
return (
<h2>{this.props.post.title}</h2>
)
}
To this:
render() {
if (!this.props.post){
return null;
}
return (
<h2>{this.props.post.title}</h2>
)
}
or
render() {
return (
<h2>{this.props.post && this.props.post.title}</h2>
)
}
You are defining allPosts to be an array
const initialState = {
allPosts: []
}
But you are trying to access it like an object.
state.allPosts.allPosts[postId]
Hence, if your state.allPosts.allPosts is an array , try using the ES6 find() method to get a post from the array with the postId.
Assuming
state.allPosts.allPosts = [
{postId: 1,title:'abcd'},
{postId:2,title:'def'}
]
state.allPosts.allPosts.find(post => postId === post.postId)
Is is correct to pass a reducer as props when i'm using a rootreducer ?
This is my rootReducer.js :
import { combineReducers } from 'redux';
import simpleReducer from './simpleReducer';
import messageReducer from './messageReducer';
import NewReducer from './NewReducer';
export default combineReducers({
simpleReducer,messageReducer,NewReducer
});
And this is one of my action creators addMessage.js
export const addMessage = (message) => dispatch => {
dispatch({
type: 'ADD',
message: message
})
}
Here is the first reducer messageReducer.js
export default (state = [], action) => {
switch (action.type) {
case 'ADD':
return [
...state,
action.message
];
default:
return state;
}
};
And here is another one simpleReducer.js
export default (state = {}, action) => {
switch (action.type) {
case 'SIMPLE_ACTION':
return {
result: action.payload
}
default:
return state
}
}
And finally here is my last reducer NewReducer.js
export default (state = '', action) => {
switch (action.type) {
case 'AnyThing':
return action.WhatToDisplay;
default:
return state;
}
};
Here is my mapping in the App.js
const mapStateToProps = state => ({
...state
})
const mapDispatchToProps = dispatch => ({
simpleAction: () => dispatch(simpleAction()),
submitNewMessage: (message) => {
dispatch(addMessage(message))
},
NewAction: () => dispatch(NewAction())
})
And here is my ِApp Component.Notice my last 2 h2 tags as well as my ul tag .Without me adding the reducer at the end of the prop , it doesn't work.So
is what i'm doing right ? or is there another way to show the redux state in
my react ?.Note that i currently have no errors and the code functions well.I
just wana know if what i am doing is right or wrong and if there is a better
syntax to show the redux state in my create react app.
class App extends Component {
constructor(props) {
super(props);
this.state = {
input: ''
}
this.handleChange = this.handleChange.bind(this);
this.submitMessage = this.submitMessage.bind(this);
}
handleChange(event) {
this.setState({
input: event.target.value
});
}
submitMessage() {
this.props.submitNewMessage(this.state.input);
this.setState({
input: ''
});
}
simpleAction = (event) => {
this.props.simpleAction();
}
localNormalFunction=(event)=>{
this.props.NewAction()
}
render() {
return (
<div >
<h1>fjasgdasdsg</h1>
<button onClick={this.simpleAction}>Test redux action</button>
<pre>
{
JSON.stringify(this.props)
}
</pre>
<h2>Type in a new Message:</h2>
<input
value={this.state.input}
onChange={this.handleChange}/><br/>
<button onClick={this.submitMessage}>Submit</button>
<ul>
{this.props.messageReducer.map( (message,idx) => {
return (
<li key={idx}>{message}</li>
)
})
}
</ul><br/><br/>
<button onClick={this.localNormalFunction}>dsadsdsa</button>
<h2>{this.props.NewReducer}</h2>
<h2>{this.props.simpleReducer.result}</h2>
</div>
);
}
}
It is better practice to get only the props you need from redux in each component. If you pass the whole redux state in mapStateToProps then whenever anything in redux changes you will have everything rerendering even if nothing you use changed.
One common reason you might be getting errors is that you are trying to use the props in render and they get instantiated afterwards.
Try this give default values to the props if you can't get them from redux:
App.defaultProps = {
result: '',
NewReducer: '',
messageReducer: []
}
const mapStateToProps = state => ({
result: state.simpleReducer.result,
NewReducer: state.NewReducer,
messageReducer: state.messageReducer
})
and then change this.props.simpleReducer.result to this.props.result
I am trying to get a simple example to work. Here is the code below.
In this example, in:
mapStateToProps = (state) => {}
where is state coming from? I am little confused as to what exactly I am passing into?
I understand that connect(mapStateToProps)(TodoApp) "binds" the state returned in mapStateToProps to TodoApp and can then be accessed via this.props.
What do I need to do to this code so I can print out the current state inside TodoApp
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { connect } from 'react-redux'
import { createStore } from 'redux'
import { combineReducers } from 'redux'
const stateObject = [
{
'id': 1,
'name': 'eric'
},
{
'id': 2,
'name': 'john'
}
]
const todo = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text
}
default:
return state
}
}
const todos = (state = stateObject, action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
];
default:
return state
}
}
const store = createStore(todos)
//confused by what is happening here
const mapStateToProps = (state) => {
return {
?: ?
}
}
const TodoApp = () => {
//How do I get this to print out the current props?
console.log(this.props)
return (
<div>
Some Text
</div>
)
}
connect(mapStateToProps)(TodoApp)
ReactDOM.render(
<Provider store={store} >
<TodoApp />
</Provider>,
document.getElementById('root')
)
Ok updated:
const mapStateToProps = (state) => {
return {
names: state
}
}
const TodoApp = () => {
console.log(this.props)
return (
<div>
Some Text1
</div>
)
}
const ConnectedComponent = connect(mapStateToProps)(TodoApp);
ReactDOM.render(
<Provider store={store} >
<ConnectedComponent />
</Provider>,
document.getElementById('root')
)
However I'm still getting undefined for console.log(this.props).
What am I doing wrong?
There's no this with a functional component. To access the props you can change it to this:
const TodoApp = (props) => {
console.log(props)
return (
<div>
Some Text1
</div>
)
}
mapStateToProps maps the some parts of your Redux state to props of your React Component.
State comes from your store. In fact, you can take a look at your current state at any point by calling store.getState(). When you do createStore(todos), this creates the state based on the todos reducer. As you can see in your todos reducer, your initial state comes from stateObject, which is defined up top.
So, back to mapStateToProps. All you need to do in that functions is to return the object, where keys will be the props and values will be the values obtained from the Redux state. Here's an example of mapStateToProps:
const mapStateToProps = function (state) {
return {
propName: state
}
}
Now when you do the console.log(this.props) inside render(), you can see the whole state being stored inside this.props.propName. That is achieved by mapStateToProps.
A little bit of theory on this: each time an action is dispatched, every mapStateToProps you have in your app is called, props are applied to every component you created, and if any props have changed, that component will re-render. This kind of behaviour is provided for you via connect function. So you don't have to implement this behaviour for every component: all you need to do is to apply it like so: const ConnectedComponent = connect(mapStateToProps)(SomeComponent) and use ConnectedComponent instead of SomeComponent.