@gyubiz141 (Yudai M)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

MERNスタックで投稿機能を実装したが、投稿内容が正しく保存されない。

解決したいこと

プログラミング初心者です。
現在、MERNスタックを使ってSNSを作成中で、
投稿時機能実装したのですが期待通りの動きをしてくれません。

お詳しい方、どこに問題があるのかご教示いただけますでしょうか。
何卒よろしくお願いいたします。

発生している問題

文言を投稿する
スクリーンショット 2022-11-04 18.08.09.png
投稿した内容はここに表示されるはすが表示されない。
スクリーンショット 2022-11-04 18.08.19.png
データーベース を確認したところ投稿内容はデーターベース に保存されていませんでした。
(投稿内容は「desc」というオブジェクトで保存されるようにAPIを作成している)
スクリーンショット 2022-11-04 18.15.11.png

【Post.js】

const PostSchema = new mongoose.Schema({
    userId: {
      type: String,
      required: true,
    },
    desc: {
      type: String,
      max: 200,
    },
    img: {
      type: String,
    },
    likes: {
      type: Array,
      default: [],
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Post", PostSchema);

【posts.js】

const router = require("express").Router();
const Post = require("../models/Post");
const User = require("../models/User");

//投稿を作成する
router.post("/", async (req, res) => {
  const newPost = new Post(req.body);
  try {
    const savedPost = await newPost.save();
    return res.status(200).json(savedPost);
  } catch (err) {
    return res.status(500).json(err);
  }
});

//etc....

【Post.jsx】

import { MoreVert } from '@mui/icons-material'
import React, { useEffect, useState, useContext } from 'react';

import "./Post.css";
// import { Users } from "../../dummyData";
import axios from "axios";
import { Link } from 'react-router-dom';
import { AuthContext } from '../../state/AuthContext';
// import { format } from ' timeago.js'; timeagoがダウンロード出来次第実装する

export default function Post({post}) {
  const PUBLIC_FOLDER = process.env.REACT_APP_PUBLIC_FOLDER;

  const [like, setLike] = useState(post.likes.length);
  const [isLiked, setIsLiked] = useState(false);
  const [user, setUser] = useState({});

  const {user: currentUser} = useContext(AuthContext);

  useEffect(() => {
    const fetchUser = async () => {
      const response = await axios.get(
        `/users?userId=${post.userId}`
      );
      // console.log(response);
      setUser(response.data);
    };
    fetchUser();
  }, [post.userId]);

  
  const handleLike = async () => {
    try {
      //いいねのAPI
      await axios.put(`/posts/${post._id}/like`, {userId: currentUser._id});
    } catch (err) {
      console.log(err);
    }


    setLike(isLiked ? like -1 : like + 1);
    setIsLiked(!isLiked);
  };

  return (
    <div className="post">
      <div className="postWrapper">
        <div className="postTop">
          <div className="postTopLeft">
            <Link to={`/profile/${user.username}`}>
              <img
                src={
                  user.profilePicture
                  ? PUBLIC_FOLDER + user.profilePicture
                  : PUBLIC_FOLDER + "/person/noAvatar.png"
                }
                alt=""
                className="postProfileImg"
              />
            </Link>
            <span className="postUsername">
              {user.username}
            </span>
            {/* <span className="postDate">{ format(post.createdAt)}</span> timeagoがダウンロード出来次第実装する */}
          </div>
          <div className="postTopRight">
            <MoreVert />
          </div>
        </div>
        <div className="postCenter">
          <span className="postText">{post.desc}</span>
          <img src={PUBLIC_FOLDER + post.img} alt="" className="postImg" />
        </div>
        <div className="postBottom">
          <div className="postBottomLeft">
            <img src={PUBLIC_FOLDER + "/heart.png"} alt="" className="likeIcon" onClick={() => handleLike()} />
            <span className="potLikeCounter">{like}人んがいいねしました。</span>
          </div>
          <div className="postBottomRight">
            <span className="postCommentText">{post.comment}:コメント</span>
          </div>
        </div>
      </div>
    </div>
  )
}

また、本件に関係があるのかはわかりませんが、コンソールに以下のようなエラーが出ていました。

react-dom.development.js:86 Warning: The tag <din> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
    at din
    at div
    at Timeline (http://localhost:3000/static/js/bundle.js:1567:5)
    at div
    at Home
    at RenderedRoute (http://localhost:3000/static/js/bundle.js:48171:5)
    at Routes (http://localhost:3000/static/js/bundle.js:48593:5)
    at Router (http://localhost:3000/static/js/bundle.js:48531:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:46863:5)
    at App (http://localhost:3000/static/js/bundle.js:42:56)
    at AuthContextProvider (http://localhost:3000/static/js/bundle.js:2767:5)
Failed to load resource: the server responded with a status of 404 (Not Found)

自分ではどこに問題があるのかが全くわかりません。
お手数をおかけしますが、問題点をご教示いただけますと幸いです。
何卒よろしくお願いいたします。

0 likes

No Answers yet.

Your answer might help someone💌