Redux Action Dispatches but does not map to state - javascript

I have An action That I am trying to use in my component, My FetchPosts() function will work and map to state, but when I use my other Action FetchUserPosts() I can see in the redux dev tools that the action dispatches, but in State nothing is there and the state doesn't change at all.
It could be something with my action but im not sure.
postAction.js
import { FETCH_POSTS, NEW_POSTS, FETCH_POST_FOR_APPROVAL,
FETCH_POSTS_FROM_USER } from './types';
export const fetchPostsFromUser = (id) => dispatch => {
Promise.all([fetch('http://10.6.254.22:5000/posts/1' + id)])
.then(([res1]) => {
return Promise.all([res1.json()])
})
.then(([posts]) => dispatch ({
type: FETCH_POSTS_FROM_USER,
payload: posts
}));
}
Types.js
export const FETCH_POSTS_FROM_USER = 'FETCH_POSTS_FROM_USER';
PostReducer.js
import { FETCH_POSTS, NEW_POSTS, FETCH_POST_FOR_APPROVAL,
FETCH_POSTS_FROM_USER } from '../actions/types';
const initialState = {
items: [],
item: {}
}
export default function (state = initialState, action ){
switch(action.type) {
case FETCH_POSTS:
console.log('currently reducing')
return{
...state,
items: action.payload
}
case NEW_POSTS:
return{
...state,
item: action.payload
}
case FETCH_POST_FOR_APPROVAL:
return{
...state,
items: action.payload
}
case FETCH_POSTS_FROM_USER:
return{
...state,
items: action.payload
}
default:
return state;
}
}
My Component I want the function to work with so i can map the props.
class ProfilePostBody extends Component {
constructor(props){
super(props)
this.state = {
commentBody: null,
postId: null,
giphyUrl: null,
postPicture: null,
userId: null,
userIdto: null,
userIdName: null,
userIdtoName:null,
// postBody: null,
// giphyUrl: null,
// userIdto: null,
// userIdName: null,
// userIdtoName:'Julio',
displayGifPicker: false
}
}
componentDidMount(){
this.props.fetchPostsFromUser();
this.props.fetchPosts();
}
render () {
return (
// <Grid item xl={6}>
<div>
{this.props.posts.map((post, index) =>
<PostBodyTemplate key={index} postId={post.id} onSubmit=
{this.handleSubmit} onChange={e =>
this.handleInputChange(e,post.id,post.userId,post.userIdName)} title=
{post.title} postBody={post.postBody}
giphyUrl = {post.giphyUrl} userWhoPosted={post.userIdName}
commentBody={post.commentBody} userIdtoName={post.userIdtoName}
userIdName={post.userIdName} />
)}
</div>
)
}
}
ProfilePostBody.propTypes = {
fetchPostsFromUser: PropTypes.func.isRequired,
fetchPosts: PropTypes.func.isRequired,
posts: PropTypes.array.isRequired
}
const mapStateToProps = state =>({
posts: state.posts.items
})
export default connect(mapStateToProps, { fetchPosts, fetchPostsFromUser
})
(ProfilePostBody);
fetchPosts will work, but if i comment it out and try just the fetchPostsFromUser() it will not work.

Related

prevstate and nextstate are the same in redux

I tried to create todo list app with react and redux but when I use "CheckTodoItem" action and log with logger, my prevstate and nextstate are same.
TodoList Action :
const AddTodoItem = ( todo ) =>{
return{
type: "ADD_TODO_ITEM",
payload: todo
}
}
const CheckTodoItem = ( todo ) =>{
return{
type: "CHECK_TODO_ITEM",
payload: todo
}
}
const DeleteTodoItem = ( todo ) =>{
return{
type: "DELETE_TODO_ITEM",
payload: todo
}
}
export { AddTodoItem, CheckTodoItem, DeleteTodoItem }
TodoLIst Reducer:
const initialState = {
todoList: [
{ todo: "workout" , isCheck: false},
{ todo: "home work" , isCheck: false},
{ todo: "pay bils" , isCheck: false},
{ todo: "visit ali" , isCheck: false},
{ todo: "Buying household items" , isCheck: false},
],
}
const todoListReducer = ( state = initialState , action ) => {
switch ( action.type ) {
case "ADD_TODO_ITEM":
const Todo = {
todo: action.payload,
isCheck: false,
};
state.todoList.push( Todo );
return{
...state
}
case "DELETE_TODO_ITEM":
const newTodoList = state.todoList.filter( item => item.todo !== action.payload)
return {
...state,
todoList: newTodoList,
}
case "CHECK_TODO_ITEM":
const objIndex = state.todoList.findIndex(( obj => obj.todo === action.payload ));
state.todoList[objIndex].isCheck = true
return{
...state,
}
default :
return state
}
}
export default todoListReducer
logger :
enter image description here
I've tried everything I can but I don't know why it's not working properly
I edit your reducer function with map :
case "CHECK_TODO_ITEM":
const todoList = state.todoList.map((todoItem)=>{
if(todoItem.todo===action.payload){
return {
...todoItem,
isCheck:true,
}else{
return todoItem
}
}
});
return{
...state,
todoList
}

React - component not updating when changed in all spots it is used

I have a Card component that shows a product and then a compare check box. If this is checked then the the item should reflect that in all areas it is shown (with a checked box). This is fine from page to page however there are a few spots that item may be displayed on a carousel and on a list for relative items. So then when that list item is clicked the same item in the carousel on the same 'page' does not update until we refresh. The code is fairly large but we have a button component inside the card component which has a function in the useEffect to watch for changes (which works fine until the item is shown twice on one page) but again it wont update unless we refresh.
I'm sharing the code for the compare button... that's really where I feel the changes are needed:
BUTTON COMPONENT
export interface LikeCompareButtonProps {
products: any[];
}
export default function LikeCompareButton({ products }: LikeCompareButtonProps) {
const dispatch = useDispatch();
const [checked, setChecked] = useState(false);
const checkProducts: any[] = useAppSelector((state) => state?.compareItems?.products)
|| [];
const checkForChange = (products: any) => {
if (compareView) {
setChecked(true);
}
if (!compareView) {
const checked = checkProducts?.find((x) => x.id === products?.id);
if (checked) {
setChecked(true);
} else {
setChecked(false);
}
}
};
const handleChange = (products: {}) => {
if (!checked) {
dispatch(setCompareItem(products));
dispatch(compareItemIncreaseCounter());
setChecked(true);
}
if (checked) {
dispatch(deleteCompareItem(products));
dispatch(compareItemDecreaseCounter());
setChecked(false);
}
getCompareItem();
};
useEffect(() => {
dispatch(getCompareItem());
dispatch(getCompareCounter());
checkForChange(products);
}, [checked]);
// hoping checked here would trigger every time it changes....
// parent component is card one. it maps through an Array -> products
return (
<div>
<button onClick={() => handleChange(products)}>
<div>
{checked && <CheckIcon className="text-white font-bold absolute h-4 w-4" />}
</div>
{!checked ? "Compare" : "Remove"}
</button>
</div>
);
}
CARD COMPONENT import Link from "next/link";
import LikeCompareButton from "../../button/like-compare-button";
export interface SmallProductCardProps {
products: any[];
}
export default function SmallProductCard({products}:
SmallProductCardProps) {
return (
<>
{products?.map((product: any, index: number) => (
<div key={product.id} >
<Link
href={
pathname: `/store/category/d/${product.id}`,
query: { item: product.id }
}}>
<a>
<img
src="http://www.innovativeengsystems.com/wp-c
ontent/uploads/2017/11/no-img-portrait.png"
alt={product.id}
/>
)}
</a>
</Link>
<LikeCompareButton
products={products[index]}
/>
</div>
))}
</>
);
}
HOME: WHERE PRODUCTS IS DEFINED
const Home: NextPage = () => {
const dispatch = useDispatch();
const products: any[] = useAppSelector((state) =>
state?.products?.products?.data);
useEffect(() => {
dispatch(getProductList()); //API RENDERED DATA
}, []);
return (
<>
<SectionLayout hero={true}>
<InnerGridViewLayout colSize={"col-span-4 grid-cols-2 grid-
rows-2 pt-0"}>
<SmallProductCard
products={products}
/>
</InnerGridViewLayout>
</SectionLayout>
</>
);
};
export default Home;
Adding REDUX work
ACTIONS
export const setCompareItem = (products: any) => {
return {
type: SET_COMPARE_ITEM,
payload: products
};
};
export const setCompareItemSuccessful = (products: any) => {
localStorage.setItem("item", JSON.stringify(products.payload));
const existingItems: any[] =
JSON.parse(localStorage.getItem("compareItems")!) ?? [];
existingItems?.push(products.payload);
localStorage.setItem("compareItems",
JSON.stringify(existingItems));
return {
type: SET_COMPARE_ITEM_SUCCESSFUL,
payload: products
};
};
export const getCompareItem = () => {
return {
type: GET_COMPARE_ITEM,
payload: []
};
};
export const getCompareItemSuccessful = () => {
var products: any[] = JSON.parse(localStorage.getItem("compareItems")!);
return {
type: GET_COMPARE_ITEM_SUCCESSFUL,
payload: products
};
};
REDUCER
import {
ERROR_COMPARE,
SET_COMPARE_ITEM,
SET_COMPARE_ITEM_SUCCESSFUL,
GET_COMPARE_ITEM,
GET_COMPARE_ITEM_SUCCESSFUL,
DELETE_COMPARE_ITEM
} from "./actionTypes";
const compareItemsState = {
products: [],
loading: false,
message: ""
};
const reducer = (state = compareItemsState, action) => {
switch (action.type) {
case SET_COMPARE_ITEM:
state = {
...state,
products: [action.payload],
message: "item added"
};
break;
case SET_COMPARE_ITEM_SUCCESSFUL:
state = {
...state,
products: [action.payload],
message: "set item success"
};
break;
case GET_COMPARE_ITEM:
state = {
...state,
products: action.payload,
message: "item found success"
};
break;
case GET_COMPARE_ITEM_SUCCESSFUL:
state = {
...state,
products: action.payload,
message: "found item"
};
break;
case DELETE_COMPARE_ITEM:
state = {
...state,
products: action.payload,
message: "item deleted"
};
break;
case ERROR_COMPARE:
state = {
...state,
compareCounter: state.compareCounter,
message: "Error adding message"
};
break;
default:
state = { ...state };
break;
}
return state;
};
export default reducer;
SAGA.tsx
import { takeEvery, fork, put, all, call } from "redux-
saga/effects";
import {
SET_COMPARE_ITEM,
SET_COMPARE_ITEM_SUCCESSFUL,
DELETE_COMPARE_ITEM,
GET_COMPARE_ITEM_SUCCESSFUL,
GET_COMPARE_ITEM,
} from "./actionTypes";
import {
compareError,
setCompareItem,
setCompareItemSuccessful,
deleteCompareItem,
getCompareItem,
getCompareItemSuccessful,
} from "./actions";
function* setCompareItems(product: any) {
try {
yield put(setCompareItem(product));
} catch (error: any) {
yield put(compareError("Item not added, please try again."));
}
}
function* setCompareItemsSuccessful(products: any) {
try {
yield put(setCompareItemSuccessful(products));
} catch (error: any) {
yield put(compareError("Item not removed, please try
again."));
}
}
function* getCompareItems() {
try {
yield put(getCompareItem());
} catch (error: any) {
yield put(compareError("please try again."));
}
}
function* getCompareItemsSuccessful() {
try {
yield put(getCompareItemSuccessful());
} catch (error: any) {
yield put(compareError("please try again."));
}
}
function* setDeleteItems(products: any) {
try {
yield put(deleteCompareItem(products));
} catch (error: any) {
yield put(compareError("Item removed"));
}
}
export function* watchSetCompareItemSuccess() {
yield takeEvery(SET_COMPARE_ITEM_SUCCESSFUL, setCompareItems);
}
export function* watchSetCompareItem() {
yield takeEvery(SET_COMPARE_ITEM, setCompareItemsSuccessful);
}
export function* watchGetCompareItemSuccess() {
yield takeEvery(GET_COMPARE_ITEM_SUCCESSFUL, getCompareItems);
}
export function* watchGetCompareItem() {
yield takeEvery(GET_COMPARE_ITEM, getCompareItemsSuccessful);
}
export function* watchDeleteCompareItem() {
yield takeEvery(DELETE_COMPARE_ITEM, setDeleteItems);
}
function* compareItemStoreSaga() {
yield all([
fork(watchSetCompareItem),
fork(watchGetCompareItem),
]);
}
export default compareItemStoreSaga;

Fetching data from server through Redux (Action & Reducer) fails to store the data in the State

I'm trying to fetch data through Redux (with actions & reducers) and store it in a ReactTable
Here is the Table :
// MisleadLeadsTable
import React from "react";
import "react-table-v6/react-table.css";
import ReactTable from "react-table-v6";
import { connect } from "react-redux";
import {
getLeadsNotValid,
updateSpecificNotValidLead
} from "../../actions/leads";
import Spinner from "../layout/Spinner";
class MisleadLeadsTable extends React.Component {
constructor(props) {
super();
const { getLeadsNotValid } = props;
// Going to get data from the Server
// Call the Action and use the Reducer
getLeadsNotValid();
// Later put the data in the state
this.state = {
data: []
};
this.renderEditable = this.renderEditable.bind(this);
}
componentDidMount() {
// TODO
const { leadsNotValid } = this.props;
this.setState({
data: leadsNotValid
});
}
// Edit the cells
renderEditable(cellInfo) {
return (
<div
style={{ backgroundColor: "#fafafa" }}
contentEditable
suppressContentEditableWarning
onBlur={e => {
const data = [...this.state.data];
data[cellInfo.index][cellInfo.column.id] = e.target.innerHTML;
this.setState({ data });
}}
dangerouslySetInnerHTML={{
__html: this.state.data[cellInfo.index][cellInfo.column.id]
}}
/>
);
}
render() {
// loading data or not
const { loadingData } = this.props;
// This "data" should hold the fetched data from the server
const { data } = this.state;
return (
<div>
{loadingData ? (
<Spinner />
) : (
<div>
<ReactTable
data={data}
columns={[
{
Header: "Business Name",
accessor: "BusinessName"
// Cell: this.renderEditable
}
]}
defaultPageSize={10}
className="-striped -highlight"
/>
<br />
</div>
)}
</div>
);
}
}
const mapStateToProps = state => ({
loadingData: state.leadReducer.loadingData,
leadsNotValid: state.leadReducer.leadsNotValid
});
const mapDispatchToProps = { getLeadsNotValid, updateSpecificNotValidLead };
export default connect(mapStateToProps, mapDispatchToProps)(MisleadLeadsTable);
However when I try to store the data in the State (in componentDidMount) it always comes back empty , and when the table is being rendered it gets an empty array.
It is crucial to store the data in the State because I'm trying to implement an editable table.
The data is stored in leadsNotValid , and if I do :
<ReactTable
data={leadsNotValid} // Notice !! Changed this
columns={[
{
Header: "Business Name",
accessor: "BusinessName"
// Cell: this.renderEditable
}
]}
defaultPageSize={10}
className="-striped -highlight"
/>
Then the data is presented successfully to the user , however it's not in the State of the component.
How can I put the leadsNotValid in the State using setState ?
Here are the Action & Reducer if it's needed (THEY WORK GREAT !) :
Action :
import axios from "axios";
import {
REQUEST_LEADS_NOT_VALID,
REQUEST_LEADS_NOT_VALID_SUCCESS,
UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID,
UPDATE_A_SINGLE_NOT_VALID_LEAD
} from "./types";
export const updateSpecificNotValidLead = updatedLead => async dispatch => {
dispatch({
type: UPDATE_A_SINGLE_NOT_VALID_LEAD
});
const config = {
headers: {
"Content-Type": "application/json"
}
};
const body = JSON.stringify({ updatedLead });
const res = await axios.post(
".......API/Something1/....",
body,
config
);
if (res !== null && res.data !== null) {
dispatch({
type: UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID
});
}
};
export const getLeadsNotValid = () => async dispatch => {
dispatch({
type: REQUEST_LEADS_NOT_VALID
});
const res = await axios.get(".......API/Something2/....");
if (res !== null && res.data !== null) {
dispatch({
type: REQUEST_LEADS_NOT_VALID_SUCCESS,
payload: res.data
});
}
};
Reducer :
import {
GET_MAIN_LEADS_SUCCESS,
REQUEST_MAIN_LEADS,
RELOAD_DATA_MAIN_LEADS_TABLE,
REQUEST_LEADS_NOT_VALID,
REQUEST_LEADS_NOT_VALID_SUCCESS,
UPDATE_A_SINGLE_NOT_VALID_LEAD,
UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID
} from "../actions/types";
const initialState = {
mainLeadsClients: [],
loadingData: null, // general loader
reloadMainLeadTable: 0,
reloadMisleadTable: 0,
leadsNotValid: []
};
export default function(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case REQUEST_LEADS_NOT_VALID:
return {
...state,
loadingData: true
};
case REQUEST_LEADS_NOT_VALID_SUCCESS:
return {
...state,
loadingData: false,
leadsNotValid: payload
};
case UPDATE_A_SINGLE_NOT_VALID_LEAD:
return {
...state,
loadingData: true
};
case UPDATED_SUCCESSFULLY_A_NOT_VALID_LEAD_THAT_NOW_IS_VALID:
return {
...state,
reloadMisleadTable: state.reloadMisleadTable + 1,
loadingData: false
};
// ... more
default:
return state;
}
}
You may have to write super(props) instead of super() in order to access props in the constructor.

Redux state is not getting initialized to initial state

I am new to the react-redux. Here, I have a reducer which is like,
const initialState = {
Low: [
{
id: 0,
technologyId: 0,
technology: '',
type: '',
count: '',
allowded: 6,
level: 'EASY'
}
],
Medium: [
{
id: 0,
technologyId: 0,
technology: '',
type: '',
count: '',
allowded: 7,
level: 'MEDIUM'
}
],
High: [
{
id: 0,
technologyId: 0,
technology: '',
type: '',
count: '',
allowded: 7,
level: 'TOUGH'
}
]
}
export default function QuizData(state = initialState, action) {
switch (action.type) {
case QUIZ_DATA:
return {
...state,
[action.data.type]: [...action.data.tobeData],
error: false,
}
case ADD_NEW:
return {
...state,
[action.data.addtype]: action.data.addData,
error: false,
}
case REMOVE_TECH:
return {
...state,
[action.data.removeType]: action.data.newArr,
error: false,
}
case RESET_QUIZ:
return {
...initialState,
error: false,
}
}
Now, Here on click of button I am calling an action that will reset the data to initial state.
this.props.resetQuiz();
which is
export function resetQuiz() {
return {
type: RESET_QUIZ
}
}
where I use it
let newData = { ...this.props.data }; while using it in the component to do some operation.
Now here what happens is after doing some actions the initial state data gets changes with some new values,..
But,on click of the button I want to set it like, initialState.
So, when I tried that time, that initialState is also getting the same values. So, It is not resetting.
I am using it in component like,
data: state.QuizData // In statetoprops.
let criterias = [{
type: 'Low',
noc: 6,
id: 1,
data: this.props.data["Low"]
}, {
type: 'Medium',
noc: 7,
id: 2,
data: this.props.data["Medium"]
},
{
type: 'High',
noc: 7,
id: 3,
data: this.props.data["High"]
}]
While using the action in component like,
createQuestionBankQuiz = () => {
this.props.resetQuiz();
history.push({
pathname: "/quiz-setup/" + `${this.props.jdId}`
});
};
export default connect(mapStateToProps, { fetchListOfQuiz, updateQuestionViewMode, enableJob, resetQuiz })(LandingScreen);
The way I update is
onChange(event, tobeupdated, id, type, noc, data) {
let newData = { ...this.props.data };
let errorState;
let isDuplicate;
let addedRow;
if (newData) {
let data = newData[type].map((object, index) => {
if (object.id === id) {
object[tobeupdated] = event.target.value;
const tobeData = newData[type];
this.props.updateLowLevel({ tobeData, type }).then(() => {
let criteria_filled = this.disableAddbutton({ ...this.props.data }, type);
addedRow = `new${type}RowAdded`;
this.setState({
[addedRow]: criteria_filled ? true : false
})
const tobechecked = newData[type].filter(item => item.id === id);
isDuplicate = this.checkPreviousSelected(newData, type, tobechecked[0].technology, tobechecked[0].type);
if (isDuplicate) {
toastr.error("Duplicate criteria. Please change it.");
object["technology"] = '';
object["type"] = '';
const tobeData = newData[type];
this.props.updateLowLevel({ tobeData, type });
}
});
}
});
errorState = `show${type}Error`;
if (tobeupdated !== "count") {
this.getSelectionQuestionsNumber(type, id, noc);
}
let validateData = this.validate(type, noc);
this.setState({
[errorState]: validateData
})
}
}
What is it that I am doing wrong ?
I think you wrong with action dispatch
export function resetQuiz() {
return dispatch => {
dispatch({
type: RESET_QUIZ
})
}
}
I think better if you try with this in reducer
export default function QuizData(state = initialState, action) {
switch (action.type) {
case RESET_QUIZ:
return Object.assign({}, initialState, {error: false})
default:
return state;
}
}
you just need to return the initial value in reducer, like this for example:
export default function QuizData(state = initialState, action) {
switch (action.type) {
case RESET_QUIZ:
return initialState
default:
return state;
}
}
You forgot to return the state in your reducer for the default action :
export default function QuizData(state = initialState, action) {
switch (action.type) {
case QUIZ_DATA:
return {
...state,
[action.data.type]: [...action.data.tobeData],
error: false,
}
case ADD_NEW:
return {
...state,
[action.data.addtype]: action.data.addData,
error: false,
}
case REMOVE_TECH:
return {
...state,
[action.data.removeType]: action.data.newArr,
error: false,
}
case RESET_QUIZ:
return {
...initialState,
error: false,
}
return state; // you forgot this
}
redux issues some kind of init action when the store is initialized, so you need to return the given state in your reducers for others actions than the ones you defined yourself.
May be you are not doing deep copy in other actions.
Can you add the code of reducer for other actions?
Edit:
Quick solution for your problems is to change your reducer like below:
export default function QuizData(state = JSON.parse(JSON.stringify(initialState)), action) {
....
}
Note: JSON.parse(JSON.stringify(initialState)) works for your case but not for all the cases, and not a good solution. You have to write deep copy logic for that.
Correct/Proper solution:
You have to modify your component logic to not modify store data directly and update it through other actions.

React.js: props.state is blank(null)

I want to Todo List in use React.js + Redux.
I make reducer file:
import { ADD_POST, REMOVE_POST } from "../actions/index.jsx";
const initialState = {
title: "",
content: ""
};
export default function Post(state = initialState, action) {
switch (action.type) {
case ADD_POST:
return [
...state,
{
id: action.id,
title: action.title,
content: action.content
}
];
case REMOVE_POST:
return state.filter(({ id }) => id !== action.id);
default:
return state;
}
}
And, I edit App.js :
class App extends Component {
render() {
return (
<div className="App">
<Input />
<List posts={this.props.allPosts} />
</div>
);
}
}
const mapStateToProps = state => {
return {
allPosts: [state.title, state.content]
};
};
export default connect(mapStateToProps, null)(App);
And, List Component is...:
render() {
return (
<div>
<ul>
{this.props.posts.map((post, index) => (
<Item {...post} key={index} />
))}
</ul>
</div>
);
}
}
I am experiencing the error "Can not read property 'map' of undefined" and can not proceed.
How can I fix it?
I'm referring to multiple sources, but I'm having difficulty because I can only see text for one 'text' state, and two sources like 'title' and 'content' states.
-------_FIX
I fix error, but props.state is blank.
I add input tag with texts but it not change everything.
-------Actions
export const ADD_POST = "ADD_POST";
export const REMOVE_POST = "REMOVE_POST";
let nextId = 0;
export function addPost(title, content) {
return {
type: ADD_POST,
id: nextId++,
title,
content
};
}
export function removePost(id) {
return {
type: REMOVE_POST,
id
};
}
I think you're confusing with the data type of your state. The below snippet might work for you. I've kept your state as an array of posts with initialState being an empty array.
So in your reducer file, initialise the initialState as:
import {
ADD_POST,
REMOVE_POST
} from "../actions/index.jsx";
const initialState = [];
export default function Post(state = initialState, action) {
switch (action.type) {
case ADD_POST:
return [
...state,
{
id: action.id,
title: action.title,
content: action.content
}
];
case REMOVE_POST:
return state.filter(({
id
}) => id !== action.id);
default:
return state;
}
}
In App.js, in the function mapStateToProps, map allPosts to state which is an array.
class App extends Component {
render() {
return (
<div className="App">
<Input />
<List posts={this.props.allPosts} />
</div>
);
}
}
const mapStateToProps = state => {
return {
allPosts: state
};
};
export default connect(mapStateToProps, null)(App);

Categories

Resources