Search code examples
reactjssearchreact-hooksaxiosmern

getting error doing a search with react and mern


I am doing a search with mern, where I type something in the form, and if it exists or equal the same we have in the backend, we display it, if else, we show a phrase not find, like a normal search

first I create a post , then I type in the other form, what I m looking for

but I am getting error when I try to fetch , in react, can someone help me, I appreciate. thanks

I am getting this error GET http://localhost:3000/post 401 (Unauthorized)

this error I set in my backend, if I type something that not exist in my db, show not find

and how can I type something that exists, how can I execute this params at react part?

import axios from "axios";
import { useState, useEffect} from "react";

function Post() {

    const [post, setPost] = useState([])
    const [click, setClick] = useState(false)
    const [currentPost, setCurrentPost] = useState("")



useEffect (() => {
    const allPost = async () => {
        const res = await axios.get("/post");
        if (setCurrentPost === post ) {
            setPost(res.data);
        } else {
            setPost("not find")
        }

    }
    
    allPost()
}, [])

return (

    <div>

        <form >
            <label></label>

            <input type="search" placeholder="Search"
            onChange={(e)=> setCurrentPost(e.target.value)}/>


        </form>


        <button onClick={()=> setClick(true)}>search</button>
            {click && post.map((post) => (

                <h1>{post.post}</h1>
            ))}


    </div>

    )
}

export default Post;

this is my backend

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


router.post("/", async (req, res) => {
    try {  
        const newPost = new Post({
            post: req.body.post
        });

        const post = await newPost.save();
        res.status(200).json(post);

    } catch(err) {
        res.status(500).json(err);
    }
});


router.get("/" ,async (req,res ) => {
    const findPost = await Post.findOne({post: req.body.post});
    if(findPost) {
        res.status(200).json(findPost);
    } else {
        res.status(401).json("not find")
    };

})

module.exports = router;

and the Schema

onst mongoose = require("mongoose")

const PostSchema = new mongoose.Schema({
    post: {
        type: String,
        required: true,
    }
}, {timestamps: true});

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

Solution

  • Assuming your intention is to search for posts and displaying results on front end.

    CLIENT_SIDE

    import axios from "axios";
    import { useState, useEffect} from "react";
    
    function Post() {
    
        const [post, setPost] = useState([])
        const [click, setClick] = useState(false)
        const [currentPost, setCurrentPost] = useState("")
    
    useEffect (() => {
        const allPost = async () => {
            const res = await axios.get(`/post?post=${currentPost}`);
            if (res && Array.isArray(res.data) ) {
                setPost(res.data);
            } 
        }    
        allPost()
    }, [currentPost])
    
    return (
    
        <div>
            <form >
                <label></label>
                <input type="search" placeholder="Search"
                onChange={(e)=> setCurrentPost(e.target.value)}/>
    
            </form>
    
            <button onClick={()=> setClick(true)}>search</button>
                {click && post.map((post) => (
                    <h1>{post.post}</h1>
                ))}
        </div>
        )
    }
    
    export default Post;
    
    
    

    BACKEND

    router.get("/" ,async (req,res ) => {
        const findPost = await Post.find({post: req.query.post});
    
        if(findPost&&findPost.length) {
            res.status(200).json(findPost);
        } else {
            res.status(200).json([]);// if not found,simply send empty array
        };
    
    })
    
    
    

    If you are not familiar with fundamentals of React or node. Please read their tutorial from their official website.