I checked my actions, reducers by console logging the payload, and I'm getting the data from my api as expected, but when I want to use my state value using useSelector hook, I have an issue.
This is my Post component where I want to use my posts state which comes from postsReducer reducer. (down below)
import React from "react";
import { useSelector } from "react-redux";
function Post() {
const posts = useSelector((state) => state.postsReducer);
console.log(posts); //undefined
return (
<>
This is a single post
</>
);
}
This is my App component where I dispatched my fetch action to get data from api. (down below)
Actions (down below)
Reducer. (down below)
All API calls are working fine.
Only the useSelector
is giving me headache !
Finally I resolved the issue, It is weird but I changed nothing, what I did, I created an index.js file inside my reducers folder for combining all the reducer files (I only had one in this case but still) and then exported that and it worked !
import { combineReducers } from "redux";
import { postsReducer } from "./posts";
const allReducers = combineReducers({postsReducer});
export default allReducers;
In some cases, a misspelling also causes the same error. For instance, your reducer could be postReducer but you access it as postsReducer
const posts = useSelector((state) => state.postsReducer);
console.log(posts); //undefined
The Provider needs to be introduced with allReducers
compined.
export const allReducers = combineReducers({
content: contentReducer,
});
let store = createStore(
allReducers,
composeWithDevTools()
);
I hate it. If this is compulsory why there are other options.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.