Having trouble implementing react-sticky component for username field - reactjs

I'm building a simple web app using React where the user enters a valid username to bring up a diary of recently eaten food items. I have a single username field at the top of the page that I want to be sticky as the user scrolls down the entirety of the page. But as it is now, the username field is just scrolling out of view like a normal component. What am I missing? Any help would be appreciated.
app.js
import React, { Component } from 'react';
import {StickyContainer, Sticky} from 'react-sticky';
import Username from '../containers/username';
import DiaryList from '../containers/diary_list';
export default class App extends Component {
render() {
return (
<div>
<h1 className="text-xs-center">Diary</h1>
<StickyContainer>
<Sticky>
{() => {
return <Username />}}
</Sticky>
<DiaryList />
</StickyContainer>
</div>
);
}
}
username.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {fetchUser} from '../actions/index';
class Username extends Component {
constructor(props){
super(props);
this.state = {term: ''};
this.onInputChange = this.onInputChange.bind(this);
}
onInputChange(event) {
this.setState({term: event.target.value},
() => this.props.fetchUser(this.state.term)
);
}
render(){
return(
<div className="username">
<span className="username-field">Username:</span>
<input value = {this.state.term}
onChange={this.onInputChange} />
</div>
)
}
}
export default connect(null, {fetchUser})(Username);
diary_list.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
import DishChart from './dish_chart';
class DiaryList extends Component {
constructor(props) {
super(props);
this.state = {width: $(window).width(),
height: $(window).height()
}
this.updateDimensions = this.updateDimensions.bind(this);
}
componentDidMount() {
window.addEventListener("resize", this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}
updateDimensions() {
this.setState({width: $(window).width(), height: $(window).height()});
}
renderDiary(diaryData, key=diaryData.dishId) {
return (
<div key={diaryData.dishId}>
<div className="col-sm-6 col-md-4 col-lg-3" >
<ul className="list-group">
<li className="list-group-item">
<img className="img-thumbnail"src={diaryData.imageLink} alt="No image available."/>
</li>
<li className="list-group-item">{diaryData.dishName}</li>
<li className="list-group-item">Price: {diaryData.price}</li>
<li className="list-group-item">Calories: {diaryData.calories}</li>
<li className="list-group-item">Health Score: {diaryData.healthScoreM}</li>
<div className="container-fluid">
<li className="list-group-item row">
<div className="col-xs-4 carbs">
{`${diaryData.carbohydrates}G Carbs`}
</div>
<div className="col-xs-4 fat">
{`${diaryData.totalFat}G Fat`}
</div>
<div className="col-xs-4 protein">
{`${diaryData.protein}G Protein`}
</div>
</li>
</div>
<li className="list-group-item recharts-wrapper">
<DishChart data={diaryData} />
</li>
</ul>
</div>
{($(window).width() >= 480 && $(window).width() < 768) &&
key % 2 == 1 &&
<div className="clearfix visible-sm-block"></div>
}
{($(window).width() >= 768 && $(window).width() < 992) &&
key % 3 == 2 &&
<div className="clearfix visible-md-block"></div>
}
{$(window).width() >= 992 &&
key % 4 == 3 &&
<div className="clearfix visible-lg-block"></div>
}
</div>
)
}
render() {
if (this.props.diary.data == undefined) {
return (
<div>
Please enter a valid username.
</div>
)
}
return (
<div className="diary">
{this.props.diary.data.map(this.renderDiary)}
</div>
);
}
}
function mapStateToProps(state) {
return {
diary: state.diary
};
}
export default connect(mapStateToProps)(DiaryList);

Related

React.js onclick button in one component change effect in other component

js
I have two buttons in parent component e.g button1 ,button2 ,and
I have two radio button in my child component e.g radio1,radio2 ,and both have class to active yellow
the task i need to do is onclick button1 in the parent component, the radio1 become active class and same on click on button2, radio2 in child become active class
import React ,{Component} from 'react';
import { withStyles } from '#material-ui/core/styles';
import { Radio } from '#material-ui/core';
import "react-datepicker/dist/react-datepicker.css";
import { connect } from 'react-redux';
import "./strip.css";
import * as actions from '../../actions/instruction';
import PaypalPayment from "./PaypalPayment"
import BankPayment from "./BankPayment"
class WidthdrawPayment extends Component {
state={
open: false,
cardId: 0,
}
setButton = (id) => {
this.setState({ cardId: id });
}
handlesChange = ({ id }) => {
//const { cardId } = this.props;
this.setState({ cardId: id });
};
render() {
const { open,cardId } = this.state;
return (
<>
<div className="main">
<div className="container-fluid no-padding">
<div style={{display: 'flex'}} >
<div
className=" lawyer-payment-big-box row">
<div className="col-md-12">
<div
className={cardId === 1 ? "active-div widthdraw-payment-choose-box col-sm-4 col-md-4 col-lg-4" :"widthdraw-payment-choose-box col-sm-4 col-lg-4 col-md-4"}>
<span>
<Radio
style={{color:'#fff'}}
color="primary"
checked={cardId === 1}
onClick={() => this.setButton(1)}
onChange={() => this.handlesChange({ id: 1 })}
name="radio-button-demo"
/>
</span>
<span className="widthdraw-payment-type-font" >Transfer</span>
</div>
<div
className={cardId === 2 ? "active-div widthdraw-payment-choose-box col-sm-4 col-md-4 col-lg-4" :"widthdraw-payment-choose-box col-sm-4 col-md-4 col-lg-4"}>
<span>
<Radio
style={{color:'#fff'}}
className=""
color="primary"
checked={cardId === 2}
onClick={() => this.setButton(2)}
onChange={()=> this.handlesChange({ id: 2 })}
name="radio-button-demo"
/>
</span>
<span className="widthdraw-payment-type-font">Bank Transfer</span>
</div>
<div className="col-md-4"></div>
</div>
{cardId === 0 ?
<div className="row">
<div style={{padding:'30px'}} className="col-md-12">
<p>Please select your payment method first to proceed</p>
</div>
</div>
:
<>
{
cardId ===1 ?
<>
{cardId ===1 &&
<PaypalPayment
{...this.props}
{...this.state}
/>
}
</>
:
<>
{/* <BankPayment
{...this.props}
{...this.state}
/> */}
{cardId ===2 ?
<>
{cardId===2 &&<BankPayment
{...this.props}
{...this.state}
/>
}
</>
:
<>
<div className="row">
<div style={{padding:'30px'}} className="col-md-12">
<p>Please select your payment method first to proceed</p>
</div>
</div>
</>
}
</>
}
</>
}
</div>
</div>
</div>
</div>
</div>
</>
)
}
}
export default WidthdrawPayment
import React from 'react';
import { withStyles } from '#material-ui/core/styles';
import { KeyboardDatePicker, MuiPickersUtilsProvider } from "#material-ui/pickers";
import DateFnsUtils from '#date-io/date-fns';
import {Link,Redirect} from 'react-router-dom';
import { Button, TYPES } from "../../components/atoms/YellowButton";
import { connect } from 'react-redux';
import moment from 'moment';
import * as actions from '../../actions/instruction';
import { EmptyList } from '../../components/molecules/NotFound/EmptyView';
import WidthdrawPayment from '../WidthdrawPayment'
const drawerWidth = 550;
class FirmPaymentStats extends React.Component {
constructor(props) {
super(props);
this.state={
open: false,
buttonId: 1,
cardId: 0,
}
this.superheroElement = React.createRef();
}
handlePaypalPayment = () => {
const {history} = this.props;
this.defaultactivepaypal()
history.push(`/main/dashboardmaster/widthdrawpayment`)
}
handleBankPayment = () => {
const {history} = this.props;
this.defaultActivebank()
history.push(`/main/dashboardmaster/widthdrawpayment`)
}
defaultactivepaypal = () => {
const {cardId} = this.props;
this.setState({ cardId: 1 });
}
defaultActivebank = () => {
const {cardId} = this.props;
this.setState({ cardId: 2 });
}
render() {
const { history,cardId } = this.props;
const { open,cardId } = this.state;
return (
<div className='main'>
<div className='container-fluid no-padding'>
<div className={classes.root}>
<div className="firm-payment-history-box row">
<div className='admin-options-section cases-section row'>
{/* balance bar */}
<div style={{ padding: '0px 30px' }} className="row">
<div class="lawyer-payment-subheading">
<div >
<p className="system-ui-bold-text firm-payment-main-heading" >Your Balance</p>
</div>
<div style={{paddingTop:'25px'}} className="lawyer-payment-subheading-btn-end">
<div className="system-ui-bold-text" style={{fontSize: "18px",padding: '8px 5px 0px 5px' }}>Widthdraw Balance:</div>
<button
className="yellow-button "
// checked={cardId === 1}
style={{display:'inline',marginRight: '10px'}}
onClick={this.handlePaypalPayment}
>
Paypal Account
</button>
<button
// checked={cardId === 2}
onClick={this.handleBankPayment}
className="yellow-button " style={{display:'inline'}}>
<img style={{marginRight:'10px'}}
src={require("../../assets/img/bank.png")} />
Bank Account
</button>
</div>
</div>
<div className='user-con-filter page-extras'>
{/* search bar and calender*/}
{/* table */}
</div>
<div className='pagination-dim'>
</div>
</div>
</div>
</div>
<div
style={{display: 'none'}}
>
<WidthdrawPayment
{...this.state}
{...this.props}
handlePaypalPayment={this.handlePaypalPayment}
handleBankPayment={this.handleBankPayment}
handleChange={ this.handlepaymenttypeChange}
/>
</div>
</div>
);
}
}
const wrappedFirmPaymentStats = withStyles(styles, { withTheme: true })(FirmPaymentStats);
const mapStateToProps = ({ instruction }) => ({
...instruction
});
export default connect(mapStateToProps, actions)(wrappedFirmPaymentStats)

Why is my component not effectively receiving props?

I keep getting a message that the item I'm trying to access via props is undefined. Can you please tell me why it's not working?
Here is where the instance where the props are attempting to be passed... I'm specifically talking about the tellus and yourTrial props.
import React from 'react'
import Info from './components/Info'
import Upsell from '../../../general/components/order/components/Upsell'
import FormTwo from '../../../general/components/forms/FormTwo'
import Footer from '../../../cbd-desktop/components/layout/Footer'
export default class Order extends React.Component {
render() {
return (
<div>
<div>
<div style={styles.header}>
<img style={styles.leaf} src="./resources/desktop-img/leaves_top.png" />
<img style={styles.logo} src="./resources/desktop-img/logo_white.png" />
</div>
<div style={styles.wrapper}>
<div style={styles.leftWrapper}>
<Info />
<Upsell styles={upsellStyles} />
</div>
<FormTwo styles={formStyles} tellus="Tell us where to send" yourTrial="YOUR TRIAL BOTTLE"} />
</div>
</div>
<Footer style={styles.footer}/>
</div>
)
}
}
And here is where I am trying to display these values on the child... towards the top in two h2s
import React from 'react'
import { connect } from 'react-redux'
import { stepTwoSubmit, saveBillingData } from
'../../actions/formStepTwoActions'
import { addReceiptProduct } from '../../actions/receiptActions'
import FormTwoInputs from './components/FormTwoInputsComponent.jsx'
import Throbber from '../throbber/Throbber'
import FormWarning from './components/FormWarningComponent.jsx'
import Button from '../../../cbd-desktop/components/layout/Button'
const mapStateToProps = state => ({
state:state,
config:state.config,
downsellProduct:state.downsell.downsellProduct || {},
receiptProducts:state.receipt.receiptProducts || []
})
const mapDispatchToProps = {
stepTwoSubmit,
saveBillingData,
addReceiptProduct
}
#connect(mapStateToProps, mapDispatchToProps)
export default class FormTwo extends React.Component {
constructor(props) {
super(props)
componentWillReceiveProps(nextProps) {
let formTwoResponse = nextProps.state.stepTwo.formTwoResponse
this.checkOrderStatus(formTwoResponse)
}
componentDidMount() {
this.fillMainOrder()
this.calculateViewers()
this.calculateTimer()
}
render() {
let { state, props, inputs, onInputFocus, saveInputVal, styles } = this,
CustomTag = props.labels ? 'label' : 'span',
{ submitting, formWarning } = state,
{ invalidInputID, text, visible } = formWarning
return (
<div style={styles.formWrapper}>
<p style={styles.yellowBanner}>{this.state.viewers} people viewing this product right now</p>
<div style={styles.formInnerWrapper}>
<div style={styles.headerWrapper}>
<h2 style={styles.header}>{this.props.tellus}</h2>
<h2 style={styles.header}>{this.props.yourTrial}</h2>
</div>
<div style={styles.weAccept}>
<p style={styles.weAcceptText}>We Accept:</p>
<img style ={styles.cardImage} src="resources/desktop-img/cards.png" />
</div>
<form onSubmit={this.submit}>
<FormTwoInputs onInputFocus={onInputFocus} saveInputVal={saveInputVal} CustomTag={CustomTag} styles={styles} />
<FormWarning visible={visible} invalidInputID={invalidInputID} text={text} />
<Button style={styles.button} buttonText="RUSH MY TRIAL" />
</form>
</div>
<img src="resources/desktop-img/secure.png" />
<div style={styles.urgencyWrapper}>
<div style={styles.urgencyTextWrapper}>
<span style={styles.redText}>{this.state.viewers} people are viewing this offer right now -</span>
<span style={styles.blueText}>{this.state.counter}</span>
</div>
<p style={styles.blueText}>Claim Your Bottle Now</p>
</div>
<Throbber throbberText='Confirming your shipment...' showThrobber={submitting} />
</div>
)
}
}

Pagination should not be rendered in every view in ReactJS?

I have 2 components 1)Content 2)Pagination
When I click on view stats button (see in screenshot) rendermatchinfo() method gets called and it shows details of single match and also shows pagination which should not be shown. Pagination must be shown only on home page where content component renders match details of all matches and not single match.
content.js :
import React, { Component } from 'react';
import Matchinfo from './matchinfo';
import './content.css';
class Content extends Component {
constructor(props){
super(props);
this.state = {
matches:[],
loading:true,
callmatchinfo: false,
matchid:''
};
}
componentDidMount(){
fetch('api/matches')
.then(res => res.json())
.then(res => {
console.log(res)
this.setState({
matches:res,
loading:false
});
})
}
viewstats(matchid){
this.setState({
callmatchinfo: true,
matchid: matchid
});
}
rendermatchinfo(){
return <Matchinfo matchid={this.state.matchid} />
}
renderMatches() {
return this.state.matches.slice(this.props.start, this.props.end).map(match => {
return (
<div className="col-lg-3">
<div id="content">
<p className="match">MATCH {match.id}</p>
<h4>{match.team1}</h4>
<p>VS</p>
<h4>{match.team2}</h4>
<div className="winner">
<h3>WINNER</h3>
<h4>{match.winner}</h4>
</div>
<div className="stats">
<button type="button" onClick= {()=>{this.viewstats(match.id)}} className="btn btn-success">View Stats</button>
</div>
</div>
</div>
);
})
}
render() {
if (this.state.loading) {
return <div>Loading...</div>
}
else if(this.state.callmatchinfo){
return <Matchinfo match_id={this.state.matchid} />
}
return (
<div>
<div className="row">
{this.renderMatches()}
</div>
<div className="row">
{this.state.callmatchinfo ? this.rendermatchinfo() : ''}
</div>
</div>
);
}
}
export default Content;
pagination.js:
import React, { Component } from 'react';
class Pagination extends Component {
handleClick(val){
this.setState({
end:val*16,
start:end-16
});
const end = val*16;
this.props.onChange(end - 16, end);
}
render() {
return (
<div>
<div className="container">
<ul className="pagination">
<li><a href="#" onClick={this.handleClick.bind(this, 1)}>1</a></li>
<li><a href="#" onClick={this.handleClick.bind(this, 2)}>2</a></li>
<li><a href="#" onClick={this.handleClick.bind(this, 3)}>3</a></li>
<li><a href="#" onClick={this.handleClick.bind(this, 4)}>4</a></li>
<li><a href="#" onClick={this.handleClick.bind(this, 5)}>5</a></li>
</ul>
</div>
</div>
);
}
}
export default Pagination;
Pagination and content component are imported in layout component.
layout.js :
import React, { Component } from 'react';
import Pagination from './pagination';
import Content from './content';
class Layout extends Component {
constructor(props){
super(props);
this.state = {
start:0,
end:16,
};
}
onChangePagination = (start, end) => {
this.setState({
start,
end
});
};
render() {
const {start, end} = this.state;
return (
<div>
<Content start={start} end={end}/>
<Pagination onChange={this.onChangePagination}/>
</div>
);
}
}
export default Layout;
Screenshot:
Home page which shows pagination :
When I click on view stats button of any particular match it still shows pagination but it should not show it.
move Pagination to Content component
Layout.js
import React, { Component } from 'react';
import Content from './content';
class Layout extends Component {
render() {
return (
<div>
<Content />
</div>
);
}
}
export default Layout;
Content.js
import React, { Component } from 'react';
import Matchinfo from './matchinfo';
import './content.css';
import Pagination from './pagination';
class Content extends Component {
constructor(props) {
super(props);
this.state = {
matches: [],
loading: true,
callmatchinfo: false,
matchid: '',
start: 0,
end: 16,
};
}
componentDidMount() {
fetch('api/matches')
.then(res => res.json())
.then(res => {
console.log(res)
this.setState({
matches: res,
loading: false
});
})
}
onChangePagination = (start, end) => {
this.setState({
start,
end
});
};
viewstats(matchid) {
this.setState({
callmatchinfo: true,
matchid: matchid
});
}
rendermatchinfo() {
return <Matchinfo matchid={this.state.matchid} />
}
renderMatches() {
return this.state.matches.slice(this.state.start, this.state.end).map(match => {
return (
<div className="col-lg-3">
<div id="content">
<p className="match">MATCH {match.id}</p>
<h4>{match.team1}</h4>
<p>VS</p>
<h4>{match.team2}</h4>
<div className="winner">
<h3>WINNER</h3>
<h4>{match.winner}</h4>
</div>
<div className="stats">
<button type="button" onClick={() => { this.viewstats(match.id) }} className="btn btn-success">View Stats</button>
</div>
</div>
</div>
);
})
}
render() {
if (this.state.loading) {
return <div>Loading...</div>
}
else if (this.state.callmatchinfo) {
return <Matchinfo match_id={this.state.matchid} />
}
return (
<div>
<div className="row">
{this.renderMatches()}
{!this.state.callmatchinfo && <Pagination onChange={this.onChangePagination} />}
</div>
<div className="row">
{this.state.callmatchinfo ? this.rendermatchinfo() : ''}
</div>
</div>
);
}
}
export default Content;
You should remove Pagination component from Layout component. Content component can be renamed as Matches component. Within the Matches component, show the Pagination component.
When view stat is clicked, show the MatchInfo component and hide the Matches and Pagination component.

Pass map's argument to function in ReactJS

I am trying to make a todoList by ReactJS. I want to delete an item by its id, but when I console.log(id), it returns undefined. Here is my code
App.js:
import React, { Component } from 'react';
import './App.css';
import Header from './Components/header';
import InputTodo from './Components/todoInput';
class App extends Component {
constructor(props){
super(props);
this.state={
todos:[
{id:0,text:'Make dinner'},
{id:1,text:'Fold the laundary'},
{id:2,text:'Do homework'}
]
}
}
addHere=(text)=>{
this.setState({
todos:this.state.todos.concat([text])
})
}
removeHere=(id)=>{
console.log(id);
// let arr=this.state.todos;
// let index=arr.findIndex((x)=>x.id===id);
// console.log(index);
}
render() {
return (
<div className='todo-wrapper'>
<Header/>
<InputTodo todoText='Type Here...' addTodo={this.addHere}/>
<div>
{this.state.todos.map((value,key)=>{
return (
<div className='row myList' key={key}>
<p className='col-xs-10'> {value.text}-{value.id} </p>
<button className='btn btn-danger pull-right col-xs-2' onClick={this.removeHere(value.id)}>Delete</button>
</div>
)})}
</div>
</div>
);
}
}
export default App;
The following is InputTodo.js:
import React, {Component} from 'react';
import '../App.css';
export default class InputTodo extends Component{
constructor(props){
super(props);
this.state={
todoInput:{
id:2,
text:''
}
}
}
handleSubmit=(e)=>{
if(this.refs.title.value===''){
alert('You must input something');
}
else{
this.state.todoInput={
id:this.state.todoInput.id+1,
text:this.refs.title.value
};
this.setState(this.state);
this.props.addTodo(this.state.todoInput);
this.refs.title.value='';
}
e.preventDefault();
}
render(){
return(
<form className='input-group' onSubmit={this.handleSubmit}>
<input type='text' ref="title" className='form-control'placeholder={this.props.todoText}/>
<span className='input-group-btn'>
<input type='submit' value='Submit' className='btn btn-primary' />
</span>
</form>
);
}
}
While FuzzyTree's answer will work, a cleaner approach would be extracting the todo item's JSX into its own component. This would have the added benefit of not creating a new function for the button's onClick prop every time App's render function gets called.
The component might look like this:
// TodoItem
class TodoItem extends Component {
handleRemove = () => this.props.onRemove(this.props.id)
render() {
return (
<div className='row myList'>
<p className='col-xs-10'> {this.props.text}-{this.props.id} </p>
<button className='btn btn-danger pull-right col-xs-2' onClick={this.handleRemove}> Delete </button>
</div>
)
}
}
// App render
render() {
return (
<div className='todo-wrapper'>
<Header/>
<InputTodo todoText='Type Here...' addTodo={this.addHere}/>
<div>
{this.state.todos.map(({ id, text }, key) =>
<TodoItem key={key} id={id} text={text} onRemove={this.removeHere} />
)}
</div>
</div>
);
}

Redux: re-rendering children on store state update

I have started to learn react + redux recently. Prior to that I have not had experience with this sort of stack.
So I ran into a problem where I do not understand why child components do not get re-rendered when reducer returns new state.
Full code on GITHUB
This is my parent component source on git:
import React from "react"
import {connect} from "react-redux"
import {fetchWarehouses} from "../../actions/warehouseActions"
import WarehouseMenu from "./WarehouseMenu"
import WarehouseView from "./WarehouseView"
import WarehouseEdit from "./WarehouseEdit"
#connect((store) => {
return {
warehouses: store.warehouses.warehouses,
selectedWarehouse: store.warehouses.selectedWarehouse,
isSelected: store.warehouses.isSelected,
warehouseCount: store.warehouses.warehouseCount,
}
})
export default class WarehousePage extends React.Component {
componentWillMount() {
this.props.dispatch(fetchWarehouses())
}
render() {
return (
<div className="container-fluid">
<div className="row">
<div className="col-sm-2">
Warehouses ({this.props.warehouseCount}):
</div>
<div className="col-sm-10">
<WarehouseMenu warehouseList={this.props.warehouses} />
</div>
</div>
<div className="col-lg-12">
<WarehouseView test={this.props.isSelected} selectedWarehouse={this.props.selectedWarehouse} />
</div>
<div className="col-lg-12">
<WarehouseEdit />
</div>
</div>
)
}
}
And these are children source on git:
import React from "react"
import store from "../../store"
import {fetchOne} from "../../actions/warehouseActions"
export default class WarehouseMenu extends React.Component {
constructor(props) {
super(props)
}
select(id) {
store.dispatch(fetchOne(id))
}
render() {
const {warehouseList} = this.props.warehouseList
if (!warehouseList) {
return <button className="btn btn-success" key="new_warehouse">+</button>
}
const mappedWarehouses = warehouseList.map(wh => <button onClick={this.select.bind(this, wh.id)} className="btn btn-default" key={wh.id}>{wh.name}</button>)
mappedWarehouses.push(<button className="btn btn-success" key="new_warehouse">+</button>)
return (
<div className="btn-group">
{mappedWarehouses}
</div>
)
}
}
And source on git:
import React from "react"
import store from "../../store"
import {deleteWarehouse, fetchWarehouses} from "../../actions/warehouseActions"
export default class WarehouseView extends React.Component {
constructor(props) {
super(props)
}
render() {
const {test, selectedWarehouse} = this.props
if (!test) {
return null
}
return (
<div className="container-fluid">
<div className="row">
<div className="col-sm-2">
ID
</div>
<div className="col-sm-10">
{selectedWarehouse.id}
</div>
</div>
<div className="row">
<div className="col-sm-2">
Name
</div>
<div className="col-sm-10">
{selectedWarehouse.name}
</div>
</div>
<div className="row">
<div className="col-sm-12">
<button className="btn btn-warning">EDIT</button>
<button onClick={this.deleteWarehouse.bind(this, selectedWarehouse.id)} className="btn btn-danger">DELETE</button>
</div>
</div>
</div>
)
}
deleteWarehouse(id) {
store.dispatch(deleteWarehouse(id))
}
}
So whenever I dispatch deleteWarehouse I want WarehouseMenu to rerender since the state of store.warehouses.warehouses changes. I do not get the expected result. Only WarehousePage rerenders (e.g. store.warehouses.warehouseCount). I've tried #connectint store to child components but did not seem to get the desired result also.
You are not alterning the warehouses property inside your warehouseReducers.js when a DELETE_WAREHOUSE_FULFILLED action is dispatched, but you do alter the warehouseCount
Your delete action:
export function deleteWarehouse(id) {
return function (dispatch) {
axios.delete(`/api/sandy/api/warehouses/${id}`)
.then((response) => {
dispatch({
type: "DELETE_WAREHOUSE_FULFILLED",
payload: null
})
})
.catch((err) => {
})
}
}
never updates the state to remove the deleted warehouse from the state.warehouses array in warehouseReducers.js:
case "DELETE_WAREHOUSE_FULFILLED": {
return {...state,
selectedWarehouse: null,
isSelected: false,
warehouseCount: state.warehouseCount - 1
}
}

Resources