I made action on my actions folder now I want to access "send new message"
to my handleSubmit function
Below is my action code :
export const types = {
MESSAGES: {
SYNC: 'MESSAGES.SYNC',
NEW: {
CHANGE: 'MESSAGES.NEW.CHANGE',
SEND: 'MESSAGES.NEW.SEND'
}
}
}
export const syncMessages = messages => ({
type: types.MESSAGES.SYNC,
messages
})
export const changeNewMessage = text => ({
type: types.MESSAGES.NEW.CHANGE,
text
})
export const sendNewMessage = () => ({
type: types.MESSAGES.NEW.SEND
})
now I want to access it on my form "handleSubmit" function
Below is my code for message.jsx file
import React from 'react';
import SubMenu from './SubMenu';
import MessageForm from './form/MessageForm';
import * as action from "../../actions/messages.actions";
export default class Messages extends React.PureComponent {
handleSubmit = (e) => {
console.log(e.target.value)
}
render() {
return (
<section className="page-notifications">
<SubMenu/>
<MessageForm onSubmit={this.handleSubmit}/>
</section>
)
}
}
Thanks in advance
import { sendNewMessage } from './path'
class Messages extends React.PureComponent {
handleSubmit = (e) => {
this.props.sendNewMessage();
}
render() {
return (
<section className="page-notifications">
<SubMenu/>
<MessageForm onSubmit={this.handleSubmit}/>
</section>
)
}
}
const mapDispatchToProps = dispatch => {
return {
// dispatching plain actions
sendNewMessage: () => dispatch(sendNewMessage()),
}
}
export default connect(
null,
mapDispatchToProps
)(Messages)
The simple way is to import your store and import dispatch from redux. Then call store.dispatch(action.sendNewMessage). Remember that the store here is your instance of store created using createStore method. But, ideal way to do it is via using react-redux.
Related
Currently, I'm using functional components with hooks but still dispatching my actions with the connect HOC.
I read through the documentation with useDispatch but I'm unsure how to incorporate it in my code. From the examples, they are passing the the action types and payloads inside the component. Would I have to move myOfferActions functions back to the component in order to useDispatch?
MyOffers component
import React, { useEffect } from "react";
import { connect, useSelector } from "react-redux";
import "./MyOffers.scss";
import MyOfferCard from "../../components/MyOfferCard/MyOfferCard";
import { fetchMyOffers } from "../../store/actions/myOffersActions";
const MyOffers = (props) => {
const myOffers = useSelector((state) => state.myOffers.myOffers);
useEffect(() => {
props.fetchMyOffers();
}, []);
return (
<div className="my-offers-main">
<h1>My offers</h1>
{myOffers && (
<div className="my-offer-container">
{myOffers.map((offer) => (
<MyOfferCard key={offer.id} offer={offer} />
))}
</div>
)}
</div>
);
};
export default connect(null, { fetchMyOffers })(MyOffers);
offerActions
export const fetchMyOffers = () => async (dispatch) => {
const userId = localStorage.getItem("userId");
try {
const result = await axiosWithAuth().get(`/offers/${userId}`);
let updatedData = result.data.map((offer) => {
//doing some stuff
};
});
dispatch(updateAction(FETCH_MY_OFFERS, updatedData));
} catch (error) {
console.log(error);
}
};
offerReducer
import * as types from "../actions/myOffersActions";
const initialState = {
offerForm: {},
myOffers: [],
};
function myOffersReducer(state = initialState, action) {
switch (action.type) {
case types.FETCH_MY_OFFERS:
return {
...state,
myOffers: action.payload,
};
default:
return state;
}
}
export default myOffersReducer;
I don't think you need connect when using the redux hooks.
You just need to call useDispatch like:
const dispatch = useDispatch();
And use the function by providing the object identifying the action:
dispatch({ type: 'SOME_ACTION', payload: 'my payload'});
It should be working with redux-thunk too (I guess this is what you're using): dispatch(fetchMyOffers())
Newbie to Redux here, I have tried to follow a couple tutorials and I am not clear of how Redux actually works. It was mentioned that the store of Redux is to store the state of the whole tree. I have created and used actions, reducers, and store for my program and it works.
The question is, how do I retrieve what is in the store? Lets say after updating my component, how can I retrieve the value inside the component and to post it?
How can I know what changed in my dropdown list and to retrieve it?
Full code in Sandbox here https://codesandbox.io/s/elated-goldberg-1pogb
store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './RootReducer';
export default function configureStore() {
return createStore(
rootReducer,
applyMiddleware(thunk)
);
}
ProductsList.js
import React from "react";
import { connect } from "react-redux";
import { fetchProducts } from "./SimpleActions";
class ProductList extends React.Component {
constructor(props)
{
super(props);
this.state = {
selecteditems: '',
unitPrice: 0
}
}
componentDidMount() {
this.props.dispatch(fetchProducts());
}
componentDidUpdate(prevProps, prevState) {
if(prevState.selecteditems !== this.state.selecteditems)
{
this.setState((state, props) => ({
unitPrice: ((state.selecteditems * 1).toFixed(2))
}));
}
}
render() {
const { error, loading, products } = this.props;
if (error) {
return <div>Error! {error.message}</div>;
}
if (loading) {
return <div>Loading...</div>;
}
return (
<div>
<select
name="sel"
className="sel"
value={this.state.selecteditems}
onChange={(e) =>
this.setState({selecteditems: e.target.value})}
>
{products.map(item =>
<option key={item.productID} value={item.unitPrice}>
{item.itemName}
</option>
)}
</select>
<p>Unit Price: RM {this.state.unitPrice} </p>
</div>
);
}
}
const mapStateToProps = state => {
const products = state.productsReducer.items;
const loading = state.productsReducer.loading;
const error = state.productsReducer.error;
return {
products,
loading,
error,
}
};
export default connect(mapStateToProps)(ProductList);
SimpleAction.js
export function fetchProducts() {
return dispatch => {
dispatch(fetchProductsBegin());
return fetch('http://localhost:55959/api/products')
.then(handleErrors)
.then(res => res.json())
.then(results => {
dispatch(fetchProductsSuccess(results));
return results;
})
.catch(error => dispatch(fetchProductsFailure(error)));
};
}
function handleErrors(response) {
if(!response.ok) {
throw Error (response.statusText);
}
return response;
}
export const FETCHPRODUCTS_BEGIN = 'FETCHPRODUCTS_BEGIN';
export const FETCHPRODUCTS_SUCCESS = 'FETCHPRODUCTS_SUCCESS';
export const FETCHPRODUCTS_FAILURE = 'FETCHPRODCUTS_FAILURE';
export const fetchProductsBegin = () => ({
type: FETCHPRODUCTS_BEGIN
});
export const fetchProductsSuccess = products => ({
type: FETCHPRODUCTS_SUCCESS,
payload: {products}
});
export const fetchProductsFailure = error => ({
type: FETCHPRODUCTS_FAILURE,
payload: {error}
});
Thanks in advance!
You will need to pass your action handlers to connect function
connect(mapStateToProps,{actions})(ProductList).
how do I retrieve what is in the store? Lets say after updating my component, how can I retrieve the value inside the component and to post it?
if you want to see how is store change, you can add redux-logger to middleware to see that. when store change, it's likely a props change, you can handle this in function componentDidUpdate.
How can I know what changed in my dropdown list and to retrieve it?
values in dropdown is controlled by "const products = state.productsReducer.items;", productsReducer is controlled by actions you passed in dispatch like this: "this.props.dispatch(fetchProducts());".
I think you should add redux-logger to know more how to redux work, it show on console step by step. It will help you learn faster than you think :D
to retrieve it you forgot the selecteditems
const mapStateToProps = state => {
const products = state.productsReducer.items;
const loading = state.productsReducer.loading;
const error = state.productsReducer.error;
const selecteditems = state.prodcuts.selecteditems;
return {
products,
loading,
error,
selecteditems
};
};
To change it you should connect another function like
const mapDispatchToProps = dispatch => {
return {
onChangeDropdownSelection: (selected)=> dispatch(actions.setSelectedDropdown(selected))
}
}
Please tell me why, when I call this.props.getOnEvents(), an error occurs that “getOnEvents() is not a function”, what’s wrong here and how to fix it?
I’m looking at the console.log and there is this function in the props, but when I try to call, an error flies out that it’s not a function
EventCalendar.js
import React, { Component } from 'react';
import { withStyles } from '#material-ui/core/styles';
import EventCalendarTable from './EventCalendarTable';
import EventCalendarView from './EventCalendarView';
const styles = theme => ({
root: {
width: '80%',
margin: '20px auto 0'
},
});
class EventCalendar extends Component {
constructor(props) {
super(props);
this.state = {
viewEvents: 'table'
};
}
componentDidMount() {
this.props.onGetEvents();
}
changeEventsView = (value) => {
this.setState({ viewEvents: value });
}
render() {
console.log(this.props);
const { classes } = this.props;
return (
<div className={classes.root}>
<EventCalendarView changeEventsView={this.changeEventsView}/>
{
this.state.viewEvents === 'table'
? <EventCalendarTable />
: <div>test</div>
}
</div>
);
}
}
export default withStyles(styles)(EventCalendar);
EventPage/component.jsx
import React from 'react';
import EventCalendar from '../../components/EventCalendar';
import './index.scss';
function Events(props) {
return (
<React.Fragment>
<EventCalendar props={props}/>
</React.Fragment>
);
}
export default Events;
EventPage/container.js
import { connect } from 'react-redux';
import EventsPage from './component';
import { getEvents } from '../../../store/modules/Events/operations';
const mapStateToProps = ({ Events }) => ({
Events
});
const mapDispatchToProps = dispatch => ({
onGetEvents: () => {
console.log(123);
dispatch(getEvents());
}
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(EventsPage);
Events/actions.js
import * as types from './types';
export const eventsFetch = value => ({
type: types.FETCHING_EVENTS,
payload: value
});
export const setEvents = ({ objById, arrayIds }) => ({
type: types.SET_EVENTS,
payload: {
eventById: objById,
eventsOrder: arrayIds
}
});
Events/types.js
export const FETCHING_EVENTS = 'Events/FETCHING_EVENTS';
export const SET_EVENTS = 'Events/SET_EVENTS';
Events/operation.js
import FetchClient from 'app/utils/FetchClient';
import IdsAndByIds from 'app/utils/IdsAndByIds';
import { eventsFetch, setEvents } from './actions';
export const getEvents = () => async (dispatch) => {
try {
const { data } = await FetchClient.get('/events');
dispatch(setEvents(IdsAndByIds(data)));
dispatch(eventsFetch(false));
} catch (error) {
console.log(error);
}
};
Events/reducer.js
import { createReducer } from 'store/utils';
import * as types from './types';
const usersInitState = {
fetching: true,
events: {
eventById: null,
usersOrder: null
},
error: null
};
const eventsReducer = createReducer(usersInitState)({
[types.FETCHING_EVENTS]: (state, { payload }) => ({
...state,
fetching: payload
}),
[types.SET_EVENTS]: (state, { payload }) => ({
...state,
events: {
...payload
}
})
});
export default eventsReducer;
Events/index.js
import { combineReducers } from 'redux';
import * as eventsListOperations from './operations';
import reducer from './reducers';
const EventsReducer = combineReducers({
eventsList: reducer
});
export default EventsReducer;
export { eventsListOperations };
The issue here is a minor one, Since you are connecting Events component to connect, you are receiveing the prop onGetEvents in that component, Now inside this component you are passing the props by a name props to the EventCalendar component
<EventCalendar props={props}/>
Now the props in EventCalender will contain a key called as props which wil lhave your data but you are trying to access it directly on props which is why it is undefined.
The correct way to pass the props here would be to use spread syntax like
<EventCalendar {...props}/>
i'm working on react-redux intermidiate..but i don't know what's going wrong
on this project
hera i have creacted the searchbar for getting car details..and the file is created as 'search.js'...you can see here..
search.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getCars } from '../actions';
import { bindActionCreators } from 'redux';
class Search extends Component{
constructor(props){
super(props);
this.state = {
keyword:''
}
}
searchCars = (event) => {
event.preventDefault();
this.props.getCars(this.state.keyword)
}
handleChange = (event) => {
this.setState({
keyword:event.target.value
})
}
componentDidMount(){
console.log(this.state);
}
render(){
return(
<div className="main_search">
<form onSubmit={this.searchCars}>
<input type="text" value={this.state.keyword} onChange = {this.handleChange} />
</form>
</div>
)
}
}
// mapStateToProps
// mapDispatchToProps
function mapDispatchToProps(dispatch){
return bindActionCreators({getCars}, dispatch)
}
export default connect(null,mapDispatchToProps)(Search);
and i think error comes from here about getCars..which is described below as s 'index.js'...you can see here
index.js
const URL_ROOT = 'http://localhost:3004'
export default function getCars(keywords){
const request = fetch(`${URL_ROOT}/carsIndex?q=${keywords}`,
{method:'GET'})
.then(response => response.json())
return{
type:'SEARCH_CARS',
payload:request
}
}
and the error looks like this..
and error showing in bundle.js file
so try to fix it and help me...
Please change your mapDispatchToProps method as
const mapDispatchToProps = (dispatch)=> (
bindActionCreators(getCars, dispatch)
)
I am trying to get a list of names stored in firebase to save to the redux store when the component loads. This list then gets sent to a dropdown component as props which are rendered as selectable options in the dropdown. For some reason I am getting 'dispatch is not defined' and I am not sure how to fix.
This is my code:
//store
import * as redux from 'redux';
import thunk from 'redux-thunk';
import {userReducer, exampleReducer, namesReducer} from 'reducers';
export var configure = (initialState = {}) => {
const reducer = redux.combineReducers({
user: userReducer,
example: exampleReducer,
names: namesReducer
})
var store = redux.createStore(reducer, initialState, redux.compose(
redux.applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
));
return store;
};
//reducers
export var namesReducer = (state = [], action) => {
switch (action.type) {
case 'GET_NAMES':
return [
action.names
]
default:
return state;
}
}
//actions
export var getNames = (names) => {
return {
type: 'GET_NAMES',
names
}
};
export var startGetNames = () => {
console.log("action started")
return (dispatch) => {
var nameRef = firebase.database().ref().child('names');
return nameRef.once('value').then((snapshot) => {
var data = snapshot.val();
_.map(data, function(name) {return finalArr.push(
{
display: `${name.first_name} ${name.last_name}`,
value: name.id
}
)});
dispatch(getNames(finalArr));
})
}
}
//component
import _ from 'underscore';
import React from 'react';
import { render } from "react-dom";
import {connect} from 'react-redux';
import Modal from 'react-responsive-modal';
var actions = require('actions');
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
//components
import roomBookingForm from 'roomBookingForm';
import PanelHeader from 'PanelHeader';
import PanelItem from 'PanelItem';
import Table from 'Table';
import TableRow from 'TableRow';
import TableHeaderCell from 'TableHeaderCell';
import TextInput from 'TextInput';
import Dropdown from 'Dropdown';
class roomBooking extends React.Component {
constructor(props) {
super(props);
this.state = {
pageTitle: "Appointment Creation",
openForm: false
}
}
componentWillMount() {
this.props.clinicians
}
onOpenModal = () => {
this.setState({openForm: true});
}
modalClose = () => {
this.setState({ openForm: false });
};
render() {
return (
<div className="main-container">
<div className="options-menu">
<PanelHeader >
Options
</PanelHeader>
<PanelItem onClick={this.onOpenModal} propClassLeft="left-item" propClassRight="right-item">Create Appointment</PanelItem>
</div>
<div>
<Table className="display-table">
<TableRow className="display-table-head">
<TableHeaderCell className="name" displayText="Name" />
</TableRow>
</Table>
</div>
<roomBookingForm open={this.state.openForm} onClose={this.modalClose} options={this.props.names} />
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
names : dispatch(actions.startGetNames())
}
export default connect()(roomBooking);
You have two correction in your code.
1.
You need to pass mapDispatchToProps in the connect call.
const mapDispatchToProps = (dispatch) => {
names : dispatch(actions.startGetNames())
}
export default connect(null,mapDispatchToProps)(roomBooking);
2.To call asynchronous action method with react-redux,the right signature is :
export var startGetNames = () => (dispatch) => {
return (dispatch) => {
//code
}
}
There are few issues with your code:
finalArr is not defined before using it.
dispatch does not work like this. It needs to be called like store.dispatch({ACTION}). So, you'll need to import store.
you should pass mapDisPatchToProps to connect function:
const mapDispatchToProps = (dispatch) => {
names : dispatch(actions.startGetNames())
}
export default connect(function(){},mapDispatchToProps)(roomBooking);