Почему компонент не обновляется через useEffect?

Я не вижу <PostWidget/> в пользовательском интерфейсе для приведенного ниже кода.

PostsWidget.jsx

import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setPosts } from "../../../Redux/Slices/authSlice";
import PostWidget from "../PostWidget";
import { userRequest } from "../../../requestMethod";

const PostsWidget = ({ userId, isProfile = false }) => {
  const dispatch = useDispatch();
  const posts = useSelector((state) => state.posts);
  console.info("posts", posts);

  const getPosts = async () => {
    const res = await userRequest.get("/posts");
    console.info("all Posts", res.data);
    dispatch(setPosts(res.data));
  };

  const getUserPosts = async () => {
    const res = await userRequest.get(`/${userId}/posts`);
    console.info("user Post", res.data);
    dispatch(setPosts(res.data));
  };

  useEffect(() => {
    if (isProfile) {
      getUserPosts();
    } else {
      getPosts();
    }
  }, []);

  return (
    <>
      {posts && posts.map(
        ({
          _id,
          userId,
          firstName,
          lastName,
          description,
          location,
          picturePath,
          userPicturePath,
          likes,
          comments,
        }) => (
          <PostWidget
            key = {_id}
            postId = {_id}
            postUserId = {userId}
            name = {`${firstName} ${lastName}`}
            description = {description}
            location = {location}
            picturePath = {picturePath}
            userPicturePath = {userPicturePath}
            likes = {likes}
            comments = {comments}
          />
        )
      )}
    </>
  );
};

export default PostsWidget;

PostWidget.jsx

const PostWidget = () => {
  return (
    <div>
      <h4>Post Widget</h4>
    </div>
  );
};

export default PostWidget;

Здесь, userRequest — это метод axios. Я написал две функции getPosts и getUserPosts для вызова API.

AuthSlice.js

import { createSlice } from "@reduxjs/toolkit";
const initialState = {
  mode: "light",
  user: null,
  token: null,
  posts: [],
};      
export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {                 
 setPosts: (state, action) => {
      state.posts = action.payload.posts;
    },
    setPost: (state, action) => {
      const updatedPosts = state.posts.map((post) => {
        if (post._id ===action.payload.post._id) {
          return action.payload.post;
        }
        return post;
      });
      state.posts = updatedPosts;
    },
  },
});

Я проверил console.infos, а также состояние редукции с помощью redux devtool. Оба показывают обновленные posts. console.info

все публикации (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]

🤔 А знаете ли вы, что...
JavaScript поддерживает работу с куки и хранилищем веб-браузера для сохранения данных на клиентской стороне.


67
1

Ответ:

Решено

Код неправильно обновляет state.posts. Так как setPosts: (state, action) => { state.posts = action.payload.posts; }, Необходимо обновить код следующим образом:

PostsWidget.jsx

  const getPosts = async () => {
    const res = await userRequest.get("/posts");
    console.info("all Posts", res.data);
    dispatch(setPosts({ posts: res.data }));
  };

  const getUserPosts = async () => {
    const res = await userRequest.get(`/${userId}/posts`);
    console.info("user Post", res.data);
    dispatch(setPosts({ posts: res.data }));
  };