• CastError: Cast to ObjectId failed for value "user" (type string) at path "_id" for model "Post"?

    @aleshaykovlev Автор вопроса
    html, css, js, node, webpack, sass, react
    React.useEffect(() => {
            let isMounted = true;
    
            async function fetchPosts(){
                try {
                    const response = await fetch(`http://localhost:5000/api/posts/user/${user._id}`, {
                        method: "GET",
                        headers: {
                            "Authorization": `Bearer ${currentUser.token}`
                        }
                    })
    
                    await response.json().then(data => {
                        if (isMounted) setPosts(data);
                    })
                } catch(e:any) {
                    alert(e.message);
                }
    
                return () => {isMounted = false};
            }
    
            user._id && fetchPosts(); // добавил проверку на существование идентификатора
        }, [currentUser.token, user._id]);
    Ответ написан
    Комментировать
  • Ошибка при отправке данных в redux?

    @aleshaykovlev Автор вопроса
    html, css, js, node, webpack, sass, react
    From: dispatch: React.Dispatch<IUser>
    export const login = (userLog: IUser, setMessage: React.Dispatch<React.SetStateAction<IMessage>>) => {
        return async (dispatch: React.Dispatch<IUser>) => {
            try {
                const response: any = await fetch("/api/auth/login", {
                    method: "POST",
                    body: JSON.stringify(userLog),
                    headers: {
                        "Content-Type": "application/json"
                    }
                });
    
                response.json().then((data: any) => {
                    dispatch(setUserAction(data.dataUser));
                    localStorage.setItem("token", data.token);
                });
            } catch(e: any) {
                setMessage({
                    text: "Ошибка сервера, попробуйте позже " + e.message,
                    type: "error"
                })
            }
        }
    }


    To: dispatch: React.Dispatch<object>
    export const login = (userLog: IUser, setMessage: React.Dispatch<React.SetStateAction<IMessage>>) => {
        return async (dispatch: React.Dispatch<object>) => {
            try {
                const response: any = await fetch("/api/auth/login", {
                    method: "POST",
                    body: JSON.stringify(userLog),
                    headers: {
                        "Content-Type": "application/json"
                    }
                });
    
                response.json().then((data: any) => {
                    dispatch(setUserAction(data.dataUser));
                    localStorage.setItem("token", data.token);
                });
            } catch(e: any) {
                setMessage({
                    text: "Ошибка сервера, попробуйте позже " + e.message,
                    type: "error"
                })
            }
        }
    }
    Ответ написан
  • Не добавляется объект в массив?

    @aleshaykovlev Автор вопроса
    html, css, js, node, webpack, sass, react
    router.post('/add/post/:id', async(req, res) => {
        try {
            const {text, img} = await req.body;
            const user = await User.findById(req.params.id);
    
            await User.updateOne({
                firstName: user.firstName,
                lastName: user.lastName,
                email: user.email,
                password: user.password,
                background: user.background,
                photo: user.photo,
                followers: user.followers
            },
            {$push: {posts: {$each: [{text, img}]}}});
    
            res.redirect('/profile/'+user._id);
        } catch (e) {
            console.log('error ' + e);
        }
    })
    Ответ написан
    Комментировать
  • Ошибка Error: Actions must be plain objects. Use custom middleware for async actions?

    @aleshaykovlev Автор вопроса
    html, css, js, node, webpack, sass, react
    Нужно добавить JSON.stringify()

    и брать payload из dispatch

    localStorage['user'] = JSON.stringify(dispatch(signIn(true)).payload);
    Ответ написан
    Комментировать
  • Ошибка при запуске сервера на react js, что делать?

    @aleshaykovlev Автор вопроса
    html, css, js, node, webpack, sass, react
    добавил переменную в среду пользователя PATH - C:\Windows\System32
    Ответ написан
    Комментировать