I have written a useReducer to update a state. when I updating state in 'userPostsReducer', the value 'action.value' is displayed. but in App() func, the value 'userPostsState' is empty, ie it is simply storing 'initial value' i give in useReducer()'s 2nd arg is useReducer's initial value only it is returning.
// app.js
const userPostsReducer = (state, action) => {
if (action.type === "USER_POSTS") {
console.log("action value: ", action.value); // value is there
return { userPosts: action.value };
}
return { userPosts: [] };
};
function App() {
..
const [userPostsState, dispatchUserPosts] = useReducer(userPostsReducer, []);
const onUserClick = useCallback(
async (id) => {
console.log("id: ", id);
if (id) {
setActiveUser(id);
setIsDataLoading(true);
const fetchedPosts = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
const postsRes = await fetchedPosts.json();
dispatchUserPosts({
type: "USER_POSTS",
value: postsRes.filter((post) => id === post.userId),
});
console.log("userPostsState: ", userPostsState); // value is empty, it is giving empty value.
setUserPosts(userPosts); // trying to update 'userPosts; with useReducer returned state for USER_POSTS action
what is wrong here?