0

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?

ram
  • 97
  • 9
  • React state updates are asynchronously processed. `useState` and `useReducer` use the same underlying update dispatcher. You can't log the enqueued state update in the same scope as the enqueueing, it won't have updated yet. – Drew Reese Sep 22 '21 at 06:36

0 Answers0