REACT-SELECT defaultValue in CustomDropdown not working - javascript

I want the default value of my dropdown to be defaultValue={item.taste} (value from match.json) but it's not working... (go to /menu/Menu1 and Pea Soup)
import Select from "react-select";
export default function CustomDropdown({ style, options, defaultValue }) {
return (
<div style={style}>
<Select options={options} defaultValue={defaultValue} />
</div>
);
}
MenuItemDisplay:
export default function MenuItemDisplay() {
const { menuId, itemId } = useParams();
const { match } = JsonData;
const matchData = match.find((el) => el._id_menu === menuId)?._ids ?? [];
const item = matchData.find((el) => el._id === itemId);
const styles = {
select: {
width: "100%",
maxWidth: 150
}
};
const TASTE = [
{ label: "Good", value: "Good" },
{ label: "Medium", value: "Medium" },
{ label: "Bad", value: "Bad" }
];
...
return (
<>
<div className="TextStyle">
{"Taste "}
<CustomDropdown
style={styles.select}
options={TASTE}
defaultValue={item.taste}
//The default value is not working only if it's
//TASTE[0]
/>
</div>
...
</>
);
}
Here the link for the code

As defaultValue you need to pass one of the objects of the TASTE array. You can do this:
<CustomDropdown
style={styles.select}
options={TASTE}
defaultValue={TASTE.find(t => t.label === item.taste)}
/>

Related

How to make several buttons simultaneously active but with some conditions?

I have a problem. I want to make buttons section, where user can click buttons to filter some content. When user click on 'all' button, all other should be turn off (change its color to initial, not active) in this moment. Also, user can check multiple buttons.
I can't get how to do this.
Example of JSON:
{
title: 'All',
id: 53,
},
{
title: 'Im a parent',
icon: <Parent />,
id: 0,
},
{
title: 'I live here',
icon: <ILiveHere />,
id: 2,
},
example of code: https://codesandbox.io/s/sleepy-haze-35htx?file=/src/App.js
Its wrong, I know. I tried some solutions, but I guess I can't get how to do it correctly.
With this code I can do active multiple buttons, but I can't get how to make conditions like
if (item.title === 'all){
TURN_OFF_ANY_OTHER_BTNS
}
I guess I should store checked buttons in temporary array to make these operations.
Will be really thankfull for help.
Is this something you would like?
const SocialRole = ({ item, selected, setSelected }) => {
let style =
[...selected].indexOf(item.id) !== -1
? { color: "red" }
: { color: "blue" };
return (
<button
style={style}
onClick={() => {
if (item.id === 53) {
setSelected(null);
} else {
setSelected(item.id);
}
}}
>
{item.icon}
<h1>{item.title}</h1>
</button>
);
};
export default function App() {
// We keep array of selected item ids
const [selected, setSelected] = useState([roles[0]]);
const addOrRemove = (item) => {
const exists = selected.includes(item);
if (exists) {
return selected.filter((c) => {
return c !== item;
});
} else {
return [...selected, item];
}
};
return (
<div>
{roles.map((item, index) => (
<SocialRole
key={index}
item={item}
selected={selected}
setSelected={(id) => {
if (id === null) setSelected([]);
else {
setSelected(addOrRemove(id));
}
}}
/>
))}
</div>
);
}
If I understand your problem, I think this is what you are looking for:
const roles = [
{
title: "All",
id: 53
},
{
title: "I live here",
id: 0
},
{
title: "I live here too",
id: 2
}
];
// button
const SocialRole = ({ item, selected, setSelected }) => {
const isActive = selected === item.title || selected === 'All';
return (
<button
style={isActive ? { color: "red" } : { color: "blue" }}
onClick={() => setSelected(item.title)}
>
{item.icon}
<h1>{item.title}</h1>
</button>
);
};
export default function App() {
const [selected, setSelected] = useState(roles[0].title);
return (
<div>
{roles.map((item, index) => (
<SocialRole
key={index}
item={item}
selected={selected}
setSelected={setSelected}
/>
))}
</div>
);
}
The problem was you were setting a new state into each button, when you should just use the state from the App.

Need a Searh Input inside react-select controll

I need an input box in the control box that search and filter the results, like this:
Input and search
Please help, I don't know how to implement this with react-select
Here is an example of implementation:
import React from "react";
import { render } from "react-dom";
import { makeData, Logo, Tips } from "./Utils";
import matchSorter from "match-sorter";
import Select from "react-select";
import "react-select/dist/react-select.css";
// Import React Table
import ReactTable from "react-table";
import "react-table/react-table.css";
class App extends React.Component {
constructor() {
super();
this.state = {
data: makeData(),
filtered: [],
select2: undefined
};
}
onFilteredChangeCustom = (value, accessor) => {
let filtered = this.state.filtered;
let insertNewFilter = 1;
if (filtered.length) {
filtered.forEach((filter, i) => {
if (filter["id"] === accessor) {
if (value === "" || !value.length) filtered.splice(i, 1);
else filter["value"] = value;
insertNewFilter = 0;
}
});
}
if (insertNewFilter) {
filtered.push({ id: accessor, value: value });
}
this.setState({ filtered: filtered });
};
render() {
const { data } = this.state;
return (
<div>
<pre>{JSON.stringify(this.state.filtered, null, 2)}</pre>
<br />
<br />
Extern Select2 :{" "}
<Select
style={{ width: "50%", marginBottom: "20px" }}
onChange={entry => {
this.setState({ select2: entry });
this.onFilteredChangeCustom(
entry.map(o => {
return o.value;
}),
"firstName"
);
}}
value={this.state.select2}
multi={true}
options={this.state.data.map((o, i) => {
return { id: i, value: o.firstName, label: o.firstName };
})}
/>
<ReactTable
data={data}
filterable
filtered={this.state.filtered}
onFilteredChange={(filtered, column, value) => {
this.onFilteredChangeCustom(value, column.id || column.accessor);
}}
defaultFilterMethod={(filter, row, column) => {
const id = filter.pivotId || filter.id;
if (typeof filter.value === "object") {
return row[id] !== undefined
? filter.value.indexOf(row[id]) > -1
: true;
} else {
return row[id] !== undefined
? String(row[id]).indexOf(filter.value) > -1
: true;
}
}}
columns={[
{
Header: "Name",
columns: [
{
Header: "First Name",
accessor: "firstName"
},
{
Header: "Last Name",
id: "lastName",
accessor: d => d.lastName
}
]
},
{
Header: "Info",
columns: [
{
Header: "Age",
accessor: "age"
},
{
Header: "Over 21",
accessor: "age",
id: "over",
Cell: ({ value }) => (value >= 21 ? "Yes" : "No"),
filterMethod: (filter, row) => {
if (filter.value.indexOf("all") > -1) {
return true;
}
if (filter.value.indexOf("true") > -1) {
return row[filter.id] >= 21;
}
return row[filter.id] < 21;
},
Filter: ({ filter, onChange }) => {
return (
<select
onChange={event => {
let selectedOptions = [].slice
.call(event.target.selectedOptions)
.map(o => {
return o.value;
});
this.onFilteredChangeCustom(selectedOptions, "over");
}}
style={{ width: "100%" }}
value={filter ? filter.value : ["all"]}
multiple={true}
>
<option value="all">Show All</option>
<option value="true">Can Drink</option>
<option value="false">Can't Drink</option>
</select>
);
}
}
]
}
]}
defaultPageSize={10}
className="-striped -highlight"
/>
<br />
<Tips />
<Logo />
</div>
);
}
}
render(<App />, document.getElementById("root"));

State Not Getting Set As Required (React, Hooks)

I am having trouble setting up a state of my component. Kindly check the details as below
Codesandbox link - https://codesandbox.io/s/goofy-glade-z32zp
This is my App Component containing 4 sub components
import React, { useState } from "react";
import "./App.css";
import RadioType from "./components/Radio/RadioQuestion";
import CheckBox from "./components/Checkbox/CheckBox";
import SelectType from "./components/SelectBox/Selectbox";
import Slider from "./components/Slider/slider";
import data from "./components/jsonData/data.json";
const App = (props) => {
const [values, setValues] = useState();
const setAnswerState = (details) => {
let newState = [];
if (values !== null && values !== undefined)
newState = JSON.parse(JSON.stringify(values));
if (newState === null || newState === undefined) {
newState = [];
newState.push(details);
} else {
if (
newState.filter((x) => x.question_id === details.question_id).length ===
0
)
newState.push(details);
else {
let indexOfFilteredObj = newState.indexOf(
newState.filter((x) => x.question_id === details.question_id)[0]
);
newState[indexOfFilteredObj] = details;
}
}
setValues(JSON.parse(JSON.stringify(newState)));
console.log(values)
};
return (
<div className="App">
{JSON.stringify(values)}
{data.map((v, i) => {
return (
<div key={i}>
{v.question_type === "radio" && (
<RadioType details={v} onChange={setAnswerState} />
)}
{v.question_type === "checkbox" && (
<CheckBox details={v} onChange={setAnswerState} />
)}
{v.question_type === "select" && (
<SelectType details={v} onChange={setAnswerState} />
)}
{v.question_type === "slider" && (
<div style={{ marginLeft: "300px" }}>
<Slider details={v} onChangeState={setAnswerState} />
</div>
)}
</div>
);
})}
</div>
);
};
export default App;
Checkbox
import React, { useState } from "react";
const CheckBox = (props) => {
const { details, onChange } = props;
const [checkedValues, setCheckedValues] = useState([]);
const setGlobalState = (value) => {
let answer = value;
let stateObj = {
question_id: details.questionId,
answers: answer,
question_type: "checkbox",
};
onChange(stateObj);
};
return (
<div>
<div>{details.question}</div>
<label>
{details.answers === undefined
? null
: details.answers.map((checkBoxAnswers, index) => {
return (
<div key={index}>
<input
type="checkbox"
name={`checkbox_${details.questionId}`}
value={checkBoxAnswers}
onChange={(e) => {
let currentValues = checkedValues;
if (e.target.checked) currentValues.push(e.target.value);
else {
const index = currentValues.indexOf(e.target.value);
if (index > -1) {
currentValues.splice(index, 1);
}
}
setCheckedValues(currentValues);
setGlobalState(currentValues);
}}
/>
<label key={index}>{checkBoxAnswers}</label>
</div>
);
})}
</label>
<br />
</div>
);
};
export default CheckBox;
Radio
import React from "react";
const RadioType = (props) => {
const { details, onChange } = props;
const setGlobalState = (value) => {
let answer = [value];
let stateObj = {
question_id: details.questionId,
answers: answer,
question_type: "radio",
};
onChange(stateObj);
};
return (
<div>
<div>{details.question}</div>
<label>
{details.answers === undefined
? null
: details.answers.map((radioQuestionAnswers, index) => {
return (
<div key={index}>
<input
type="radio"
name={`radio_${details.questionId}`}
value={radioQuestionAnswers}
onChange={(e) => setGlobalState(e.target.value)}
/>
<label key={index}>{radioQuestionAnswers}</label>
</div>
);
})}
</label>
<br />
</div>
);
};
export default RadioType;
Select
import React from "react";
const SelectType = (props) => {
const { details, onChange } = props;
const setGlobalState = (value) => {
let answer = [value];
let stateObj = {
question_id: details.questionId,
answers: answer,
question_type: "select",
};
onChange(stateObj);
};
return (
<>
<div>{details.question}</div>
<select
name={`checkbox_${details.questionId}`}
onChange={(e) => {
setGlobalState(e.target.value);
}}
>
{details.answers === undefined
? null
: props.details.answers.map((selectAns, index) => {
return (
<option key={index} value={selectAns}>
{selectAns}
</option>
);
})}
</select>
</>
);
};
export default SelectType;
NouiSlider
import React from "react";
import Nouislider from "nouislider-react";
import "nouislider/distribute/nouislider.css";
const Slider = (props) => {
const { details, onChangeState } = props;
const setGlobalState = (value) => {
let answer = [value];
let stateObj = {
question_id: details.questionId,
answers: answer,
question_type: "slider",
};
onChangeState(stateObj);
};
return (
<>
<Nouislider
style={{ color: "red", width: "600px" }}
start={[0]}
pips={{ mode: "count", values: details.division }}
clickablePips
range={{
min: details.range.min,
max: details.range.max,
}}
onChange={(e) => {
let valueOfSlider = parseFloat(e[0]);
setGlobalState(valueOfSlider);
}}
/>
</>
);
};
export default Slider;
Coming to the problem whenever I try to set state from the radio checkbox or select it does set the state and updates correctly via setAnswerState method that is passed as prop to child. Whenever I try to change the slider the setAnswerState gets values as undefined or null, so the complete state that is set by other child components is lost, I am not able to find the reason behind state lost.
Here is the sample data I used for testing
[
{
"question": "When was the Cilivar War?",
"question_type": "radio",
"answers": ["1877-1866", "1877-1872", "1877-1851", "1877-1880"],
"questionId": "099011"
},
{
"question": "World's Largest country by population?",
"answers": ["China", "Canada", "United kingdom", "India"],
"correctAns": "China",
"question_type": "checkbox",
"dependent_question_id": [
{
"question_id": "099011",
"answers_to_match": [
{
"operator": "AND",
"answers": ["1877-1866"]
}
]
}
],
"questionId": "0990758"
},
{
"question": "Where is the Tajmahal?",
"answers": ["Agra", "Mumbai", "Pune", "Punjab"],
"correctAns": "Agra",
"question_type": "select",
"dependent_question_id": [
{
"question_id": "099011",
"answers_to_match": [
{
"operator": "AND",
"answers": ["1877-1866"]
}
]
},
{
"question_id": "099078",
"answers_to_match": [
{
"operator": "AND",
"answers": ["Canada", "United kingdom"]
}
]
}
],
"questionId": "099096"
},
{
"questionId": "0002346",
"question_type": "slider",
"division": 5,
"range":
{
"min": 0,
"max": 100
}
}
]
Just add [] in useState() as shown below:
const [values, setValues] = useState([]);
And then update the setAnswerState method to:
const setAnswerState = (details) => {
// below statement will handle both the cases:
// updating an existing question as well as adding in a new question
setValues((prevValues) => [
...prevValues.filter((x) => x.question_id !== details.question_id),
{ ...details }
]);
};
In your App Component, you need to add [] in useState() as
const [values, setValues] = useState([]);
and inside setAnswerState(), use the newState as the value of setValues().
setValues(newState)
not
setValues(JSON.parse(JSON.stringify(newState)));

Why can't property map be read?

I am trying to iterate through an array of objects to display all items of a certain name. For some reason my this.props.list.items cannot be read. Any help would be greatly appreciated.
The code for item.js
import React from "react";
class Item extends React.Component{
render() {
return(
<div>{this.props.list.items}</div>
)
}
}
export default Item
The code for horizontalscroll.js
import React from 'react';
import ScrollMenu from 'react-horizontal-scrolling-menu';
import './horizontalscroll.css';
import Item from './Item';
// list of items
const list = [
{
name: "Brands",
items: ["1", "2", "3"]
},
{
name: "Films",
items: ["f1", "f2", "f3"]
},
{
name: "Holiday Destination",
items: ["f1", "f2", "f3"]
}
];
// One item component
// selected prop will be passed
const MenuItem = ({ text, selected }) => {
return (
<div
className="menu-item"
>
{text}
</div>
);
};
// All items component
// Important! add unique key
export const Menu = (list) => list.map(el => {
const { name } = el;
return (
<MenuItem
text={name}
key={name}
/>
);
});
const Arrow = ({ text, className }) => {
return (
<div
className={className}
>{text}</div>
);
};
const ArrowLeft = Arrow({ text: '<', className: 'arrow-prev' });
const ArrowRight = Arrow({ text: '>', className: 'arrow-next' });
class HorizantScroller extends React.Component {
state = {
selected: 0
};
onSelect = key => {
this.setState({ selected: key });
}
render() {
const { selected } = this.state;
// Create menu from items
const menu = Menu(list, selected);
return (
<div className="HorizantScroller">
<ScrollMenu
data={menu}
arrowLeft={ArrowLeft}
arrowRight={ArrowRight}
selected={selected}
onSelect={this.onSelect}
/>
<div>{this.props.items.map((item) => {
return <Item item={item}/>
})}
</div>
</div>
);
}
}
export default HorizantScroller;
Inside Item, you should access it like this
<div>{this.props.item}</div>
Because when rendering Item, you did <Item item={item}/>

The data sent from action is not received by reducer

I am using redux with my react application. I am trying to get the data from my reducer but when I am trying to do this. I am getting some error.
Uncaught Error: Given action "RECEIVE_CATEGORY_NAME", reducer
"categoriesReducer" returned undefined. To ignore an action, you must
explicitly return the previous state. If you want this reducer to hold
no value, you can return null instead of undefined.
the logic written is working fine in case of influencersNameReducer but is showing an error for categoriesReducer
home_reducer.js
import { RECEIVE_INFLUENCERS_NAME, RECEIVE_CATEGORY_NAME } from './home_actions';
export const influencersNameReducer = (state = [], { type, influencers }) => {
console.log(influencers)
return type === RECEIVE_INFLUENCERS_NAME ? influencers : state
}
export const categoriesReducer = (state = [], { type, category }) => {
console.log(type, category)
return type === RECEIVE_CATEGORY_NAME ? category : state
}
home_actions.js
export const RECEIVE_INFLUENCERS_NAME = 'RECEIVE_INFLUENCERS_NAME'
export const RECEIVE_CATEGORY_NAME = 'RECEIVE_CATEGORY_NAME';
const receiveInfluencersName = influencers => ({ type: RECEIVE_INFLUENCERS_NAME, influencers })
const receiveCategoryName = categories => ({ type: RECEIVE_CATEGORY_NAME, categories })
export const fetchInfluencers = _ => dispatch => {
$.ajax({
method: 'get',
url: 'vip_api/influencers',
data: { name: _ },
success(influencers) {
dispatch(receiveInfluencersName(influencers))
},
error({ responseJSON, statusText }) {
dispatch(receiveServerErrors(responseJSON || [statusText]))
}
})
}
export const fetchCategories = _ => dispatch => {
$.ajax({
method: 'get',
url: 'vip_api/categories',
data: { name: _ },
success(categories) {
dispatch(receiveCategoryName(categories))
},
error({ responseJSON, statusText }) {
dispatch(receiveServerErrors(responseJSON || [statusText]))
}
})
}
store.js
import {influencersNameReducer, categoriesReducer} from './Vvip/Home/home_reducer';
import { composeWithDevTools } from 'redux-devtools-extension';
const reducer = combineReducers({
categoriesReducer,
influencersNameReducer,
})
const composeEnhancers = composeWithDevTools({
// Specify name here, actionsBlacklist, actionsCreators and other options if needed
});
export default (state = {}) => (
createStore(reducer, state, composeEnhancers(applyMiddleware(errorMiddleware, timeoutMiddleware, thunk)))
)
index.js
import React, { Component } from 'react'
import Select, { components } from 'react-select'
import DateRange from '../../shared/_date_range';
import moment from 'moment';
import {ethnicities, ageRanges, isoCountries} from '../../constants';
import { connect } from 'react-redux';
import {fetchInfluencers, fetchCategories} from './home_actions';
class InfluencersForm extends Component {
constructor() {
super();
this.state = {
demography: null,
dates : {
startDate: moment(),
endDate: moment()
},
influencersName: [],
}
}
handleInfluencerName = event => {
this.props.dispatch(fetchInfluencers(event))
}
handleSelectedInfluencer = event => {
console.log(event)
this.setState({
isMenuOpenInfluencer : false
})
}
componentWillReceiveProps(newProps) {
console.log(newProps);
if (newProps.influencersNameReducer && newProps.influencersNameReducer.length) {
this.setState({
influencersName: newProps.influencersNameReducer.map((influencer, index) => {
return ({ value: influencer, label: influencer })
}),
})
}
}
handleInfluencerType = event => {
console.log(event)
}
handleInfluencerCountry = event => {
console.log(event)
}
handleInfluencerSubscribers = event => {
console.log(event)
}
handleInfluencerVideosCreated = event => {
console.log(event)
}
handleInfluencerCategory = event => {
console.log(event)
this.props.dispatch(fetchCategories(event))
}
onDemographyChange = event => {
console.log(event.currentTarget.value)
this.setState({
demography: event.currentTarget.value
})
}
handleInfluencerAge = event => {
console.log(event)
}
handleInfluencerGender = event => {
console.log(event)
}
handleInfluencerEthnicity = event => {
console.log(event)
}
updateDates = event => {
console.log(event)
this.setState({
dates: event
})
}
render() {
const influencersType = [
{ value: 'a', label: 'Type A' },
{ value: 'b', label: 'Type B' },
{ value: 'c', label: 'Type C' }
]
const influencersCategory = [
{ value: 'a', label: 'Type A' },
{ value: 'b', label: 'Type B' },
{ value: 'c', label: 'Type C' }
]
const influencersAge = ageRanges.map(age => ({ value: age, label: age }))
const influencersGender = [
{ value: 'male', label: 'Male' },
{ value: 'female', label: 'Female' }
]
const influencersKeywords = [
{ value: 'youtuber', label: 'Youtuber' },
{ value: 'vlogger', label: 'Vlogger' }
]
const influencersCountry = Object.keys(isoCountries).map(code => ({ value: code, label: isoCountries[code] }))
const DropdownIndicator = (props) => {
return components.DropdownIndicator && (
<components.DropdownIndicator {...props}>
<i className="fa fa-search" aria-hidden="true" style={{ position: 'initial', color: 'black' }}></i>
</components.DropdownIndicator>
);
};
return (
<div className='home-forms influencer-form'>
<div className='display-flex'>
<Select
options={this.state.influencersName}
onChange={this.handleSelectedInfluencer}
closeMenuOnSelect = {true}
isSearchable={true}
components={{ DropdownIndicator }}
onInputChange = {this.handleInfluencerName}
placeholder={'Start Typing Influencers Name'}
classNamePrefix="vyrill"
className="influencers influencers-icon-name" />
<Select
options={influencersType}
onChange={this.handleInfluencerType}
placeholder='Type of Influencers'
classNamePrefix="vyrill"
className="influencers influencers-icon-type" />
<Select
options={influencersCountry}
onChange={this.handleInfluencerCountry}
isSearchable={true}
components={{ DropdownIndicator }}
placeholder='Start Typing Country'
classNamePrefix="vyrill"
className="influencers influencers-icon-country" />
</div>
<div className='display-flex' style={{ marginTop: 32 }}>
<Select
options={influencersType}
onChange={this.handleInfluencerSubscribers}
placeholder='Number of Subscribers'
classNamePrefix="vyrill"
className="influencers influencers-icon-type" />
<Select
options={influencersType}
onChange={this.handleInfluencerVideosCreated}
placeholder='Number of Videos Created'
classNamePrefix="vyrill"
className="influencers influencers-icon-videos-created" />
<Select
options={influencersCategory}
onChange={this.handleInfluencerCategory}
onInputChange = {this.handleInfluencerCategory}
isSearchable={true}
components={{ DropdownIndicator }}
placeholder='Start Typing Category'
classNamePrefix="vyrill"
className="influencers influencers-icon-country influencers-icon-category" /> {/* remove influencers-icon-country later */}
</div>
<div style={{ marginTop: 50 }}>
<div className="display-flex">
<div className="icon-subscribers" style={{ marginTop: 4 }}></div>
<div style={{ fontWeight: 700, marginTop: 4 }}>Demographics</div>
<div className="radio-container">
<label>
<div style={{ fontSize: 14, marginTop: 4 }}>By influencers</div>
<input
type="radio"
name="demographics"
value="influencers"
checked={this.state.demography === 'influencers'}
onChange={this.onDemographyChange} />
<span className="custom-radio">
</span>
</label>
</div>
<div className="radio-container">
<label>
<div style={{ fontSize: 14, marginTop: 4 }}>By people in videos</div>
<input
type="radio"
name="demographics"
value="people in videos"
checked={this.state.demography === 'people in videos'}
onChange={this.onDemographyChange} />
<span className="custom-radio"></span>
</label>
</div>
</div>
</div>
<div className="display-flex" style={{ marginTop: 40 }}>
<Select
options={influencersAge}
onChange={this.handleInfluencerAge}
placeholder='Age'
classNamePrefix="vyrill"
className="influencers" />
<Select
options={influencersGender}
onChange={this.handleInfluencerGender}
placeholder='Gender'
classNamePrefix="vyrill"
className="influencers" />
<Select
options={ethnicities}
onChange={this.handleInfluencerEthnicity}
placeholder='Ethnicity'
classNamePrefix="vyrill"
className="influencers" />
</div>
<div style={{marginTop: 50}}>
<div style={{display: 'inline'}}>Contains keywords (in transcript):</div>
<span className="icon-info"></span>
<Select
options={influencersKeywords}
onChange={this.handleInfluencerName}
isSearchable={true}
classNamePrefix="vyrill"
placeholder= {" "}
className="influencers influencers-keywords"
styles = {{marginTop: 10}}/>
</div>
<div style={{marginTop: 50}} className="date-picker">
<div>Posted content time range</div>
<DateRange dates={ this.state.dates } updateDates={ this.updateDates }/>
<div className="icon-arrow-right"></div>
</div>
</div>
)
}
}
const mapStateToProps = ({ influencersNameReducer, categoriesReducer }) => ({
influencersNameReducer,
categoriesReducer
})
export default connect(mapStateToProps)(InfluencersForm)
You need to modify your reducer as:
export const influencersNameReducer = (state = [], { type, influencers }) => {
switch(type) {
case RECEIVE_INFLUENCERS_NAME:
return influencers;
default:
return state;
}
}
export const categoriesReducer = (state = [], { type, category }) => {
switch(type) {
case RECEIVE_CATEGORY_NAME:
return category;
default:
return state;
}
}
On every action the dispatcher goes to every reducer. Since in your code the influencersNameReducer reducer was not doing anything for type RECEIVE_CATEGORY_NAME thus returning undefined. So you were getting the error. Using switch case is the way to do this.

Categories