Giter Site home page Giter Site logo

adrianhajdin / social_media_app Goto Github PK

View Code? Open in Web Editor NEW
1.1K 8.0 330.0 2.49 MB

Build a modern social app with a stunning UI with a native mobile feel, a special tech stack, an infinite scroll feature, and amazing performance using React JS, Appwrite, TypeScript, and more.

Home Page: https://jsmastery.pro

HTML 0.44% JavaScript 1.38% TypeScript 92.25% CSS 5.92%
appwrite react reactjs

social_media_app's Introduction


Project Banner
react.js appwrite tailwindcss reactquery typescript

A Social Media Application

Build this project step by step with our detailed tutorial on JavaScript Mastery YouTube. Join the JSM family!
  1. πŸ€– Introduction
  2. βš™οΈ Tech Stack
  3. πŸ”‹ Features
  4. 🀸 Quick Start
  5. πŸ•ΈοΈ Snippets
  6. πŸ”— Links
  7. πŸš€ More

🚨 Tutorial

This repository contains the code corresponding to an in-depth tutorial available on our YouTube channel, JavaScript Mastery.

If you prefer visual learning, this is the perfect resource for you. Follow our tutorial to learn how to build projects like these step-by-step in a beginner-friendly manner!

Explore social media with this user-friendly platform that has a nice look and lots of features. Easily create and explore posts, and enjoy a strong authentication system and quick data fetching using React Query for a smooth user experience.

If you're getting started and need assistance or face any bugs, join our active Discord community with over 27k+ members. It's a place where people help each other out.

  • React.js
  • Appwrite
  • React Query
  • TypeScript
  • Shadcn
  • Tailwind CSS

πŸ‘‰ Authentication System: A robust authentication system ensuring security and user privacy

πŸ‘‰ Explore Page: Homepage for users to explore posts, with a featured section for top creators

πŸ‘‰ Like and Save Functionality: Enable users to like and save posts, with dedicated pages for managing liked and saved content

πŸ‘‰ Detailed Post Page: A detailed post page displaying content and related posts for an immersive user experience

πŸ‘‰ Profile Page: A user profile page showcasing liked posts and providing options to edit the profile

πŸ‘‰ Browse Other Users: Allow users to browse and explore other users' profiles and posts

πŸ‘‰ Create Post Page: Implement a user-friendly create post page with effortless file management, storage, and drag-drop feature

πŸ‘‰ Edit Post Functionality: Provide users with the ability to edit the content of their posts at any time

πŸ‘‰ Responsive UI with Bottom Bar: A responsive UI with a bottom bar, enhancing the mobile app feel for seamless navigation

πŸ‘‰ React Query Integration: Incorporate the React Query (Tanstack Query) data fetching library for, Auto caching to enhance performance, Parallel queries for efficient data retrieval, First-class Mutations, etc

πŸ‘‰ Backend as a Service (BaaS) - Appwrite: Utilize Appwrite as a Backend as a Service solution for streamlined backend development, offering features like authentication, database, file storage, and more

and many more, including code architecture and reusability

Follow these steps to set up the project locally on your machine.

Prerequisites

Make sure you have the following installed on your machine:

Cloning the Repository

git clone https://github.com/adrianhajdin/social_media_app.git
cd social_media_app

Installation

Install the project dependencies using npm:

npm install

Set Up Environment Variables

Create a new file named .env in the root of your project and add the following content:

VITE_APPWRITE_URL=
VITE_APPWRITE_PROJECT_ID=
VITE_APPWRITE_DATABASE_ID=
VITE_APPWRITE_STORAGE_ID=
VITE_APPWRITE_USER_COLLECTION_ID=
VITE_APPWRITE_POST_COLLECTION_ID=
VITE_APPWRITE_SAVES_COLLECTION_ID=

Replace the placeholder values with your actual Appwrite credentials. You can obtain these credentials by signing up on the Appwrite website.

Running the Project

npm start

Open http://localhost:3000 in your browser to view the project.

constants.index.ts
export const sidebarLinks = [
  {
    imgURL: "/assets/icons/home.svg",
    route: "/",
    label: "Home",
  },
  {
    imgURL: "/assets/icons/wallpaper.svg",
    route: "/explore",
    label: "Explore",
  },
  {
    imgURL: "/assets/icons/people.svg",
    route: "/all-users",
    label: "People",
  },
  {
    imgURL: "/assets/icons/bookmark.svg",
    route: "/saved",
    label: "Saved",
  },
  {
    imgURL: "/assets/icons/gallery-add.svg",
    route: "/create-post",
    label: "Create Post",
  },
];

export const bottombarLinks = [
  {
    imgURL: "/assets/icons/home.svg",
    route: "/",
    label: "Home",
  },
  {
    imgURL: "/assets/icons/wallpaper.svg",
    route: "/explore",
    label: "Explore",
  },
  {
    imgURL: "/assets/icons/bookmark.svg",
    route: "/saved",
    label: "Saved",
  },
  {
    imgURL: "/assets/icons/gallery-add.svg",
    route: "/create-post",
    label: "Create",
  },
];
globals.css
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap");

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  * {
    @apply box-border list-none p-0 m-0 scroll-smooth;
  }

  body {
    @apply bg-dark-1 text-white min-h-screen font-inter;
  }
}

@layer utilities {
  /* TYPOGRAPHY */
  .h1-bold {
    @apply text-[36px] font-bold leading-[140%] tracking-tighter;
  }

  .h1-semibold {
    @apply text-[36px] font-semibold leading-[140%] tracking-tighter;
  }

  .h2-bold {
    @apply text-[30px] font-bold leading-[140%] tracking-tighter;
  }

  .h3-bold {
    @apply text-[24px] font-bold leading-[140%] tracking-tighter;
  }

  .base-semibold {
    @apply text-[16px] font-semibold leading-[140%] tracking-tighter;
  }

  .base-medium {
    @apply text-[16px] font-medium leading-[140%];
  }

  .base-regular {
    @apply text-[16px] font-normal leading-[140%];
  }

  .body-bold {
    @apply text-[18px] font-bold leading-[140%];
  }

  .body-medium {
    @apply text-[18px] font-medium leading-[140%];
  }

  .small-semibold {
    @apply text-[14px] font-semibold leading-[140%] tracking-tighter;
  }

  .small-medium {
    @apply text-[14px] font-medium leading-[140%];
  }

  .small-regular {
    @apply text-[14px] font-normal leading-[140%];
  }

  .subtle-semibold {
    @apply text-[12px] font-semibold leading-[140%];
  }

  .tiny-medium {
    @apply text-[10px] font-medium leading-[140%];
  }

  /* UTILITIES */
  .invert-white {
    @apply invert brightness-0 transition;
  }

  .flex-center {
    @apply flex justify-center items-center;
  }

  .flex-between {
    @apply flex justify-between items-center;
  }

  .flex-start {
    @apply flex justify-start items-center;
  }

  .custom-scrollbar::-webkit-scrollbar {
    width: 3px;
    height: 3px;
    border-radius: 2px;
  }

  .custom-scrollbar::-webkit-scrollbar-track {
    background: #09090a;
  }

  .custom-scrollbar::-webkit-scrollbar-thumb {
    background: #5c5c7b;
    border-radius: 50px;
  }

  .custom-scrollbar::-webkit-scrollbar-thumb:hover {
    background: #7878a3;
  }

  .common-container {
    @apply flex flex-col flex-1 items-center gap-10 overflow-scroll py-10 px-5 md:px-8 lg:p-14 custom-scrollbar;
  }

  /* All Users */
  .user-container {
    @apply max-w-5xl flex flex-col items-start w-full gap-6 md:gap-9;
  }

  .user-grid {
    @apply w-full grid grid-cols-1 xs:grid-cols-2 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3 gap-7 max-w-5xl;
  }

  /* Explore */
  .explore-container {
    @apply flex flex-col flex-1 items-center overflow-scroll py-10 px-5 md:p-14 custom-scrollbar;
  }

  .explore-inner_container {
    @apply max-w-5xl flex flex-col items-center w-full gap-6 md:gap-9;
  }

  .explore-search {
    @apply h-12 bg-dark-4 border-none placeholder:text-light-4 focus-visible:ring-0 focus-visible:ring-offset-0 ring-offset-0 !important;
  }

  /* Home */
  .home-container {
    @apply flex flex-col flex-1 items-center gap-10 overflow-scroll py-10 px-5 md:px-8 lg:p-14 custom-scrollbar;
  }

  .home-posts {
    @apply max-w-screen-sm flex flex-col items-center w-full gap-6 md:gap-9;
  }

  .home-creators {
    @apply hidden xl:flex flex-col w-72 2xl:w-465 px-6 py-10 gap-10  overflow-scroll custom-scrollbar;
  }

  /* Post Details */
  .post_details-container {
    @apply flex flex-col flex-1 gap-10 overflow-scroll py-10 px-5 md:p-14 custom-scrollbar items-center;
  }

  .post_details-card {
    @apply bg-dark-2 w-full max-w-5xl rounded-[30px] flex-col flex xl:flex-row border border-dark-4 xl:rounded-l-[24px];
  }

  .post_details-img {
    @apply h-80 lg:h-[480px] xl:w-[48%] rounded-t-[30px] xl:rounded-l-[24px] xl:rounded-tr-none object-cover p-5 bg-dark-1;
  }

  .post_details-info {
    @apply bg-dark-2 flex flex-col gap-5 lg:gap-7 flex-1 items-start p-8 rounded-[30px];
  }

  .post_details-delete_btn {
    @apply p-0 flex gap-3 hover:bg-transparent hover:text-light-1  text-light-1 small-medium lg:base-medium;
  }

  /* Profile */
  .profile-container {
    @apply flex flex-col items-center flex-1 gap-10 overflow-scroll py-10 px-5 md:p-14 custom-scrollbar;
  }

  .profile-inner_container {
    @apply flex items-center md:mb-8 xl:items-start gap-8 flex-col xl:flex-row relative max-w-5xl w-full;
  }

  .profile-tab {
    @apply flex-center gap-3 py-4 w-48 bg-dark-2  transition flex-1 xl:flex-initial;
  }

  /* Saved */
  .saved-container {
    @apply flex flex-col flex-1 items-center gap-10 overflow-scroll py-10 px-5 md:p-14 custom-scrollbar;
  }

  /* Bottom bar */
  .bottom-bar {
    @apply z-50 flex-between w-full sticky bottom-0 rounded-t-[20px] bg-dark-2 px-5 py-4 md:hidden;
  }

  /* File uploader */
  .file_uploader-img {
    @apply h-80 lg:h-[480px] w-full rounded-[24px] object-cover object-top;
  }

  .file_uploader-label {
    @apply text-light-4 text-center small-regular w-full p-4 border-t border-t-dark-4;
  }

  .file_uploader-box {
    @apply flex-center flex-col p-7 h-80 lg:h-[612px];
  }

  /* Grid Post List */
  .grid-container {
    @apply w-full grid grid-cols-1 sm:grid-cols-2 md:grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-7 max-w-5xl;
  }

  .grid-post_link {
    @apply flex rounded-[24px] border border-dark-4 overflow-hidden cursor-pointer w-full h-full;
  }

  .grid-post_user {
    @apply absolute bottom-0 p-5 flex-between w-full bg-gradient-to-t from-dark-3 to-transparent rounded-b-[24px] gap-2;
  }

  /* Left sidebar */
  .leftsidebar {
    @apply hidden md:flex px-6 py-10 flex-col justify-between min-w-[270px] bg-dark-2;
  }

  .leftsidebar-link {
    @apply rounded-lg base-medium hover:bg-primary-500 transition;
  }

  /* Post Card */
  .post-card {
    @apply bg-dark-2 rounded-3xl border border-dark-4 p-5 lg:p-7 w-full max-w-screen-sm;
  }

  .post-card_img {
    @apply h-64 xs:h-[400px] lg:h-[450px] w-full rounded-[24px] object-cover mb-5;
  }

  /* Topbar */
  .topbar {
    @apply sticky top-0 z-50 md:hidden bg-dark-2 w-full;
  }

  /* User card */
  .user-card {
    @apply flex-center flex-col gap-4 border border-dark-4 rounded-[20px] px-5 py-8;
  }
}

@layer components {
  /* SHADCN COMPONENTS */
  /* Form */
  .shad-form_label {
    @apply text-white !important;
  }

  .shad-form_message {
    @apply text-red !important;
  }

  .shad-input {
    @apply h-12 bg-dark-4 border-none placeholder:text-light-4 focus-visible:ring-1 focus-visible:ring-offset-1 ring-offset-light-3 !important;
  }

  .shad-textarea {
    @apply h-36 bg-dark-3 rounded-xl border-none focus-visible:ring-1 focus-visible:ring-offset-1 ring-offset-light-3 !important;
  }

  /* Button */
  .shad-button_primary {
    @apply bg-primary-500 hover:bg-primary-500 text-light-1 flex gap-2 !important;
  }

  .shad-button_dark_4 {
    @apply h-12 bg-dark-4 px-5 text-light-1 flex gap-2 !important;
  }

  .shad-button_ghost {
    @apply flex gap-4 items-center justify-start hover:bg-transparent hover:text-white !important;
  }
}
queryKeys.ts
export enum QUERY_KEYS {
  // AUTH KEYS
  CREATE_USER_ACCOUNT = "createUserAccount",

  // USER KEYS
  GET_CURRENT_USER = "getCurrentUser",
  GET_USERS = "getUsers",
  GET_USER_BY_ID = "getUserById",

  // POST KEYS
  GET_POSTS = "getPosts",
  GET_INFINITE_POSTS = "getInfinitePosts",
  GET_RECENT_POSTS = "getRecentPosts",
  GET_POST_BY_ID = "getPostById",
  GET_USER_POSTS = "getUserPosts",
  GET_FILE_PREVIEW = "getFilePreview",

  //  SEARCH KEYS
  SEARCH_POSTS = "getSearchPosts",
}
tailwind.config.js
/** @type {import('tailwindcss').Config} */
const defaultTheme = require('tailwindcss/defaultTheme')

module.exports = {
  darkMode: ['class'],
  content: [
    './pages/**/*.{ts,tsx}',
    './components/**/*.{ts,tsx}',
    './app/**/*.{ts,tsx}',
    './src/**/*.{ts,tsx}',
  ],
  theme: {
    container: {
      center: true,
      padding: '2rem',
      screens: {
        '2xl': '1400px',
      
      },
    },
    extend: {
      colors: {
        'primary-500': '#877EFF',
        'primary-600': '#5D5FEF',
        'secondary-500': '#FFB620',
        'off-white': '#D0DFFF',
        'red': '#FF5A5A',
        'dark-1': '#000000',
        'dark-2': '#09090A',
        'dark-3': '#101012',
        'dark-4': '#1F1F22',
        'light-1': '#FFFFFF',
        'light-2': '#EFEFEF',
        'light-3': '#7878A3',
        'light-4': '#5C5C7B',
      },
      screens: {
        'xs': '480px',
      
      },
      width: {
        '420': '420px',
        '465': '465px',
      },
      fontFamily: {
        inter: ['Inter', 'sans-serif'],

      },
      keyframes: {
        'accordion-down': {
          from: { height: 0 },
          to: { height: 'var(--radix-accordion-content-height)' },
        },
        'accordion-up': {
          from: { height: 'var(--radix-accordion-content-height)' },
          to: { height: 0 },
        },
      },
      animation: {
        'accordion-down': 'accordion-down 0.2s ease-out',
        'accordion-up': 'accordion-up 0.2s ease-out',
      },
    },
  },
  plugins: [require('tailwindcss-animate')],
};
types.index.ts
export type INavLink = {
  imgURL: string;
  route: string;
  label: string;
};

export type IUpdateUser = {
  userId: string;
  name: string;
  bio: string;
  imageId: string;
  imageUrl: URL | string;
  file: File[];
};

export type INewPost = {
  userId: string;
  caption: string;
  file: File[];
  location?: string;
  tags?: string;
};

export type IUpdatePost = {
  postId: string;
  caption: string;
  imageId: string;
  imageUrl: URL;
  file: File[];
  location?: string;
  tags?: string;
};

export type IUser = {
  id: string;
  name: string;
  username: string;
  email: string;
  imageUrl: string;
  bio: string;
};

export type INewUser = {
  name: string;
  email: string;
  username: string;
  password: string;
};
useDebounce.ts
import { useEffect, useState } from "react";

// https://codesandbox.io/s/react-query-debounce-ted8o?file=/src/useDebounce.js
export default function useDebounce<T>(value: T, delay: number): T {
  // State and setters for debounced value
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    // Update debounced value after delay
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    // Cancel the timeout if value changes (also on delay change or unmount)
    // This is how we prevent debounced value from updating if value is changed ...
    // .. within the delay period. Timeout gets cleared and restarted.
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]); // Only re-call effect if value or delay changes

  return debouncedValue;
}
utils.ts
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

export const convertFileToUrl = (file: File) => URL.createObjectURL(file);

export function formatDateString(dateString: string) {
  const options: Intl.DateTimeFormatOptions = {
    year: "numeric",
    month: "short",
    day: "numeric",
  };

  const date = new Date(dateString);
  const formattedDate = date.toLocaleDateString("en-US", options);

  const time = date.toLocaleTimeString([], {
    hour: "numeric",
    minute: "2-digit",
  });

  return `${formattedDate} at ${time}`;
}

// 
export const multiFormatDateString = (timestamp: string = ""): string => {
  const timestampNum = Math.round(new Date(timestamp).getTime() / 1000);
  const date: Date = new Date(timestampNum * 1000);
  const now: Date = new Date();

  const diff: number = now.getTime() - date.getTime();
  const diffInSeconds: number = diff / 1000;
  const diffInMinutes: number = diffInSeconds / 60;
  const diffInHours: number = diffInMinutes / 60;
  const diffInDays: number = diffInHours / 24;

  switch (true) {
    case Math.floor(diffInDays) >= 30:
      return formatDateString(timestamp);
    case Math.floor(diffInDays) === 1:
      return `${Math.floor(diffInDays)} day ago`;
    case Math.floor(diffInDays) > 1 && diffInDays < 30:
      return `${Math.floor(diffInDays)} days ago`;
    case Math.floor(diffInHours) >= 1:
      return `${Math.floor(diffInHours)} hours ago`;
    case Math.floor(diffInMinutes) >= 1:
      return `${Math.floor(diffInMinutes)} minutes ago`;
    default:
      return "Just now";
  }
};

export const checkIsLiked = (likeList: string[], userId: string) => {
  return likeList.includes(userId);
};

Assets used in the project are here

Advance your skills with Next.js 14 Pro Course

Enjoyed creating this project? Dive deeper into our PRO courses for a richer learning adventure. They're packed with detailed explanations, cool features, and exercises to boost your skills. Give it a go!

Project Banner

Accelerate your professional journey with the Expert Training program

And if you're hungry for more than just a course and want to understand how we learn and tackle tech challenges, hop into our personalized masterclass. We cover best practices, different web skills, and offer mentorship to boost your confidence. Let's learn and grow together!

Project Banner

social_media_app's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

social_media_app's Issues

Getting error in useGetPosts.

Since this Api was most crucial, so I wrote what was shown in video. But sill I was getting this. I tried the doc. But wasn't able to figure out, where I was wrong. Can anyone help me with this.

This is in src>lib>react-queries>queries.ts

export const useGetPosts = () => {
return useInfiniteQuery({
queryKey: [QUERY_KEYS.GET_INFINITE_POSTS],
queryFn: getInfinitePosts,
getNextPageParam: (lastPage) => {
// If there's no data, there are no more pages.
if (lastPage && lastPage.documents.length === 0) {
return null;
}
// Use the $id of the last document as the cursor.
const lastId = lastPage?.documents[lastPage.documents.length - 1].$id;
return lastId;
},
});
};

The error message from vercel:

image

not getting redirected upon signing up

I did each and everything same till 2 hrs and 06 mins, everything on the appwrite side is working properly, the database is being created but only upon creating a user, I'm not getting redirected to the homepage.

AuthContext.tsx

import { getCurrentUser } from "@/lib/appwrite/api";
import { IContextType, IUser } from "@/types";
import { createContext, useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";

export const INITIAL_USER = {
   id: "",
   name: "",
   username: "",
   email: "",
   imageUrl: "",
   bio: "",
};

const INITIAL_STATE = {
   user: INITIAL_USER,
   isLoading: false,
   isAuthenticated: false,
   setUser: () => {},
   setIsAuthenticated: () => {},
   checkAuthUser: async () => false as boolean,
};

const AuthContext = createContext<IContextType>(INITIAL_STATE);

const AuthProvider = ({ children }: { children: React.ReactNode }) => {
   const [user, setUser] = useState<IUser>(INITIAL_USER);
   const [isLoading, setIsLoading] = useState(false);
   const [isAuthenticated, setIsAuthenticated] = useState(false);

   const navigate = useNavigate();

   const checkAuthUser = async () => {
      setIsLoading(true);
      try {
         const currentAccount = await getCurrentUser();

         if (currentAccount) {
            setUser({
               id: currentAccount.$id,
               name: currentAccount.name,
               username: currentAccount.username,
               email: currentAccount.email,
               imageUrl: currentAccount.imageUrl,
               bio: currentAccount.bio,
            });

            setIsAuthenticated(true);

            return true;
         }

         return false;
      } catch (error) {
         console.log(error);
         return false;
      } finally {
         setIsLoading(false);
      }
   };

   useEffect(() => {
      // localStorage.getItem('cookieFallback') === null
      if (
         localStorage.getItem('cookieFallback') === '[]'
      ) navigate("/sign-in");
      

      checkAuthUser();
   }, []);

   const value = {
      user,
      setUser,
      isLoading,
      isAuthenticated,
      setIsAuthenticated,
      checkAuthUser,
   };

   return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export default AuthProvider;

export const useUserContext = () => useContext(AuthContext);

Followed along tutorial, now everything is black on sign-up

So I was working along line for line character for character, but then happened something that didn't happen in the video. As we consoleloged the asnyc function onSubmit everything went right. But Asap I switched to the local host and provided faked account infos to check if the console is giving feedback the whole page went black and the error was:

appwrite.js?v=2d49613e:707 Uncaught TypeError: Cannot read properties of undefined (reading 'replace')
at Client.setEndpoint (appwrite.js?v=2d49613e:707:89)
at config.ts:11:8

If someone can help me please do it!

stuck on the create user api

I am getting error when creating user account

Screenshot 2023-11-16 at 20 25 50

All the appwrite configurations are same. Couldn't find out the issue here!
Screenshot 2023-11-16 at 20 27 33

Screenshot 2023-11-16 at 20 27 52 Screenshot 2023-11-16 at 20 28 08

Cannot signin

I was doing everything perfect till this timestamp 02:05:43 .. now the problem is ... I was thrown with an error in the terminal saying "api.ts:58 Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint." instead of going to the 'RootLayout" page . Can anyone please tell me why ?
sample

can anyone ..help me to rectify this?

"No overload matches this call"

image

I'm running into a problem during deployment. I get this No overload matches this call error.

Found this.

It says I'm passing a parameter that doesn't match the specified overloads.

Thing is, my code is identical to the finished project.

Sigin Signup Not working

While Done with the signin and signup part after doing both activities its giving failed to sign in and Signup

Unable to implement delete post feature.

While implementing the delete post function i am unable to delete it. Below given is the snapshots of the code, the main handler is in the 'postDetail-ss' mutation function is in 'queryAndMutations-ss' and api is in 'API-ss' while debugging i found that the api-function is not being executed. Kindly help with this problem, any help and guidance will be appreciated.
postDetail-ss

queryAndMutations-ss

API-ss

AppwriteException: Document with the requested ID could not be found. api.ts:264

β–ΊGET https://cloud.appwrite.io/v1/databases/6580fe3.../collections/6586 api.ts:254 534.../documents/undefined 404 (Not Found) AppwriteException: Document with the requested ID could not be found. api.ts:264 at Client. (http://localhost:5173/node modules/.vite/deps/appwrite.js? v=639e56a2:850:17) at Generator.next () at fulfilled (http://localhost: 5173/node modules/.vite/deps/appwrite.js?v=639e56a 2:488:24) Query data cannot be undefined. Please make sure to return a value console.js:213 other than undefined from your query function. Affected query key: ["getPostById", "undefined"]

I have trouble with the edit post in the social media app project. In the tutorial the data automatically got populated in editpost except the image but in my case it doesn't.

Errors:
I'm getting an GET error 404 for appwrite document ID and also getting query 'getPostById' to undefined

So in api.ts getPostById I checked that it's returning databaseID and postCollectionID from appwriteconfig but not the postId and that's why the post.

But I don't know why

Please help

License

What is the license for the code and the assets?

The app crashed, appwrite error 401

Everything seemed to be working fine, but now I am getting this error, when I try to perform the basic functionalities like page refresh, logout, save post, even when starting the app.
api401

Post Details Class Error

PostDetails.jsx @ d044bd9
Line 106 has:

className={`ost_details-delete_btn ...

This should be:

className={`post_details-delete_btn ...

missing required parameter file.

`export async function createPost(post: INewPost) {
try {
//upload image to storage
const uploadedFile = await uploadFile(post.file[0]);

if (!uploadedFile) {
  throw Error;
}
// Get file url
const fileUrl = getFilePreview(uploadedFile.$id);

if (!fileUrl) {
  deleteFile(uploadedFile.$id);
  throw Error;
}
// convert tags into an array
const tags = post.tags?.replace(/ /g, "").split(",") || [];

// save post to database
const newPost = await databases.createDocument(
  appwriteConfig.databaseId,
  appwriteConfig.postsCollectionId,
  ID.unique(),
  {
    creator: post.userId,
    caption: post.caption,
    location: post.location,
    imageUrl: fileUrl,
    imageId: uploadedFile?.$id,
    tags: tags,
  }
);
if (!newPost) {
  await deleteFile(uploadedFile?.$id);
  throw Error;
}
return newPost;

} catch (error) {
console.log(error);
}

}`

i am recieving this in error

cant create post

please fix with my problem am getting problem in creating the post

Error on isLoading Property . If anyone has answers drop them I appreciate it :) Thank you

Everywhere isLoading property is used . I get this error and i have no idea how to tackle this. If i use chatgpt it completely alters my code.
The error:
Property 'isLoading' does not exist on type 'UseMutationResult<Session | undefined, Error, { email: string; password: string; }, unknown>'.ts(2339)
This happens on Signinform, signupform, UpdatProfile, Postform
Property 'isLoading' does not exist on type 'UseMutationResult<Session | undefined, Error, { email: string; password: string; }, unknown>'.ts(2339)
issue while deployment

@adrianhajdin can i please get some help here?

Screenshot 2024-03-02 145841

@adrianhajdin can i please get some help here?
i have attached the screenshot of localhost and console together....
the problem is not that nothing is appearing in the home page (thats because i havent started building the home page yet) but the problem is that even if i put the url as localhost:5173/sign-in or localhost:5173/sign-up, its getting redirected to localhost:5173...... i really dont have that much grip over development that i can figure out myself that where is the error among so many lines of code.... plz do consider helping out...

Vercel Deployment Error

i've been trying to work this out but no luck. Any advice is appreciated. This is the error vercel gives me when deployment fails:
[18:07:31.024] Running build in Washington, D.C., USA (East) – iad1
[18:07:31.144] Cloning github.com/GTierra2000/snapgram (Branch: main, Commit: 27be4f6)
[18:07:31.154] Skipping build cache, deployment was triggered without cache.
[18:07:31.507] Cloning completed: 362.856ms
[18:07:31.770] Running "vercel build"
[18:07:34.857] Vercel CLI 33.2.0
[18:07:35.690] Installing dependencies...
[18:07:48.636] npm ERR! code 1
[18:07:48.637] npm ERR! path /vercel/path0/node_modules/vite/node_modules/esbuild
[18:07:48.638] npm ERR! command failed
[18:07:48.638] npm ERR! command sh -c node install.js
[18:07:48.638] npm ERR! node: /lib64/libm.so.6: version GLIBC_2.27' not found (required by node) [18:07:48.638] npm ERR! node: /lib64/libc.so.6: version GLIBC_2.27' not found (required by node)
[18:07:48.639] npm ERR! node: /lib64/libc.so.6: version `GLIBC_2.28' not found (required by node)
[18:07:48.640]
[18:07:48.640] npm ERR! A complete log of this run can be found in: /vercel/.npm/_logs/2024-02-03T23_07_36_083Z-debug-0.log
[18:07:48.661] Error: Command "npm install" exited with 1
[18:07:48.853]

user is sending update post request even there is no change in any fields

    if (post && action === 'Update') {
      const updatedPost = await updatePost({
        ...value,
        postId: post.$id,
        imageId: post.imageId,
        imageUrl: post.imageUrl,
      });
      if (!updatedPost) {
        return toast({ title: 'please try again' });
      }
      return navigate(`/posts/${post.$id}`);
    }
    const newPost = await createPost({ ...value, userId: user.id });
    if (!newPost) {
      toast({
        title: `${action} post failed. Please try again.`,
      });
    }
    navigate('/');
  };

I can't see the home page

image

console log error message :
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["getRecentPosts"]

getting an internal server error on deleting a post.

As far as I have debugged the code the problem lies in the postId and the imageId. it says that files are not passing to the function. plus I have added videoId for video posts and comments in the post schema. I'm passing those IDs as well but still not working.

here is the API function :

export async function deletePost(post) {

  if (!post?.postId || !post?.imageId || !post?.videoId ) {
    console.error('Invalid post data for deletion');
    return { status: 'error', message: 'Invalid post data for deletion' };
  }

  try {
    const statusCode = await databases.deleteDocument(
      appwriteConfig.databaseId,
      appwriteConfig.postCollectionId,
      post?.postId
    );

    if (!statusCode) throw Error;

      await deleteFile(post?.imageId)

      if(post?.videoId) {
        await deleteFile(post?.videoId)
      }

    return { status: "ok" };

  } catch (error) {
    console.log(error);
  }
}

this is the handleDelete function i m calling the post details:


const handleDeletePost = () => {
    try {
      const deletedPost = deletePost({
        post,
        postId: postId,
        imageId: post?.imageId,
        videoId: post?.videoId,
      });
  
      if (deletedPost && deletedPost.status === 'ok') {
        router.push('/');
      } else {
        console.error('Failed to delete post.');
        // Optionally, you can show an error message or handle the failure in another way.
      }
    } catch (error) {
      console.error('Error deleting post:', error);
      // Handle the error accordingly, e.g., show an error message to the user.
    }
  };

this is the mutation fn:


export const useDeletePost = () => {
  const queryClient  = useQueryClient();

  return useMutation({
    mutationFn: (post) => deletePost(post),
    onSuccess: (data) => {
      queryClient.invalidateQueries({
        queryKey: ['getRecentPosts', data.$id],
      });
    }
  })
}

additionally, I think that in appwrite, adrian set delete as null in other document, tell me if it will remain true for comments as well or i have to cahnge it to cascade.

I face issue in EditPost

Web capture_29-1-2024_211230_localhost
Anyone know hoe to solve this issue console log shows

Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["getPostById","undefined"]

GET https://cloud.appwrite.io/v1/databases/65b3b2ba6cff73041202/collections/65b3b349ac07991b84d8/documents/undefined 404 (Not Found)

when I check Route path I saw "http://localhost:5173/update-post/undefined" when I remove undefined and paste postId then show results!!!

Complain

Blank screen while creating signup form, and console is saying the issue is coming from appwrite.js which i tried debugging but it seem lots is hidden in the video in node_modules

Cannot get account from appwrite

When the code in the file config.ts executes this line
const currentAccount = await account.get()
it does not connect to Appwrite, in the console shows this:

image

Does anyone have the same issue?

bank screen

Hello guys, I have a problem with posts, after making a post the screen goes blank, even when i try to refresh it just goes blank
Image 2024-01-11 at 02 23

can not signup and signin AppwriteExpetion: Invalid document structure:Missing required attribute "accountid"

content-script.js:104 Failed to get subsystem status for purpose Object
cloud.appwrite.io/v1/databases/6544e479aba1454ec652/collections/xxxxx/documents?queries%5B0%5D=equal%28%22accountId%22%2C+%5B%22654a3509ab1a622c22da%22%5D%29:1

   Failed to load resource: the server responded with a status of 400 ()

api.ts:100 AppwriteException: Invalid query: Attribute not found in schema: accountId
at Client. (http://localhost:5173/node_modules/.vite/deps/appwrite.js?v=7d826b09:850:17)
at Generator.next ()
at fulfilled (http://localhost:5173/node_modules/.vite/deps/appwrite.js?v=7d826b09:488:24)
cloud.appwrite.io/v1/databases/6544e479aba1454ec652/collections/6544e5b07a9561cbc689/documents?queries%5B0%5D=equal%28%22accountId%22%2C+%5B%22654a3509ab1a622c22da%22%5D%29:1

   Failed to load resource: the server responded with a status of 400 ()

api.ts:100 AppwriteException: Invalid query: Attribute not found in schema: accountId
at Client. (http://localhost:5173/node_modules/.vite/deps/appwrite.js?v=7d826b09:850:17)
at Generator.next ()
at fulfilled (http://localhost:5173/node_modules/.vite/deps/appwrite.js?v=7d826b09:488:24)
client.ts:425 Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.
(anonymous) @ client.ts:425
cloud.appwrite.io/v1/databases/xxxx/collections/xxxxx/documents:1

   Failed to load resource: the server responded with a status of 400 ()

api.ts:57 AppwriteException: Invalid document structure: Missing required attribute "accountid"
at Client. (http://localhost:5173/node_modules/.vite/deps/appwrite.js?v=7d826b09:850:17)
at Generator.next ()
at fulfilled (http://localhost:5173/node_modules/.vite/deps/appwrite.js?v=7d826b09:488:24)
image

Rotation values lost? Postform to Posted

Hello

Problem solving something with image rotation. When a user creates a post with a photo the preview window that shows the photo is working great. ondrop / dropzone. FileUplaoder. However if the photo has rotation / uploaded from mobile it will loose whatever is working in the preview. PostForm onSubmit. The images are correct in the Appwrite DB preview. Something is ignoring their rotation or loosing that rotation when it pulls them back down and draws them in the social media app (doesn't matter if it's a grid or a profile picture, etc). I've been working on it for days, BlueImp / EXIF / etc and haven't been able to make a change to the rotation that carries over to the saved / posted file.

Any hints or tips to help me look at how to solve this would be greatly appreciated. And thank you. Your tutorial and source code really helped me a lot. Feel free to check out what you help me build.

Nupperson.com

and.... help! :)

An error in useGetPosts in queries.ts

I am getting an error in queries.ts file as:

No overload matches this call.
Overload 1 of 3, '(options: UndefinedInitialDataInfiniteOptions<DocumentList | undefined, Error, InfiniteData<DocumentList | undefined, unknown>, QUERY_KEYS[], any>, queryClient?: QueryClient | undefined): UseInfiniteQueryResult<...>', gave the following error.
Argument of type '{ queryKey: QUERY_KEYS.GET_INFINITE_POSTS[]; queryFn: ({ pageParam }: { pageParam: number; }) => Promise<Models.DocumentList<Models.Document> | undefined>; getNextPageParam: (lastPage: any) => any; }' is not assignable to parameter of type 'UndefinedInitialDataInfiniteOptions<DocumentList | undefined, Error, InfiniteData<DocumentList | undefined, unknown>, QUERY_KEYS[], any>'.
Property 'initialPageParam' is missing in type '{ queryKey: QUERY_KEYS.GET_INFINITE_POSTS[]; queryFn: ({ pageParam }: { pageParam: number; }) => Promise<Models.DocumentList<Models.Document> | undefined>; getNextPageParam: (lastPage: any) => any; }' but required in type 'UseInfiniteQueryOptions<DocumentList | undefined, Error, InfiniteData<DocumentList | undefined, unknown>, DocumentList<...> | undefined, QUERY_KEYS[], any>'.
Overload 2 of 3, '(options: DefinedInitialDataInfiniteOptions<DocumentList | undefined, Error, InfiniteData<DocumentList | undefined, unknown>, QUERY_KEYS[], any>, queryClient?: QueryClient | undefined): DefinedUseInfiniteQueryResult<...>', gave the following error.
Argument of type '{ queryKey: QUERY_KEYS.GET_INFINITE_POSTS[]; queryFn: ({ pageParam }: { pageParam: number; }) => Promise<Models.DocumentList<Models.Document> | undefined>; getNextPageParam: (lastPage: any) => any; }' is not assignable to parameter of type 'DefinedInitialDataInfiniteOptions<DocumentList | undefined, Error, InfiniteData<DocumentList | undefined, unknown>, QUERY_KEYS[], any>'.
Property 'initialPageParam' is missing in type '{ queryKey: QUERY_KEYS.GET_INFINITE_POSTS[]; queryFn: ({ pageParam }: { pageParam: number; }) => Promise<Models.DocumentList<Models.Document> | undefined>; getNextPageParam: (lastPage: any) => any; }' but required in type 'UseInfiniteQueryOptions<DocumentList | undefined, Error, InfiniteData<DocumentList | undefined, unknown>, DocumentList<...> | undefined, QUERY_KEYS[], any>'.
Overload 3 of 3, '(options: UseInfiniteQueryOptions<DocumentList | undefined, Error, InfiniteData<DocumentList | undefined, unknown>, DocumentList<...> | undefined, QUERY_KEYS[], any>, queryClient?: QueryClient | undefined): UseInfiniteQueryResult<...>', gave the following error.
Argument of type '{ queryKey: QUERY_KEYS.GET_INFINITE_POSTS[]; queryFn: ({ pageParam }: { pageParam: number; }) => Promise<Models.DocumentList<Models.Document> | undefined>; getNextPageParam: (lastPage: any) => any; }' is not assignable to parameter of type 'UseInfiniteQueryOptions<DocumentList | undefined, Error, InfiniteData<DocumentList | undefined, unknown>, DocumentList<...> | undefined, QUERY_KEYS[], any>'.
Property 'initialPageParam' is missing in type '{ queryKey: QUERY_KEYS.GET_INFINITE_POSTS[]; queryFn: ({ pageParam }: { pageParam: number; }) => Promise<Models.DocumentList<Models.Document> | undefined>; getNextPageParam: (lastPage: any) => any; }' but required in type 'UseInfiniteQueryOptions<DocumentList | undefined, Error, InfiniteData<DocumentList | undefined, unknown>, DocumentList<...> | undefined, QUERY_KEYS[], any>'.ts(2769)
queryClient-aPcvMwE9.d.ts(324, 5): 'initialPageParam' is declared here.
queryClient-aPcvMwE9.d.ts(324, 5): 'initialPageParam' is declared here.
queryClient-aPcvMwE9.d.ts(324, 5): 'initialPageParam' is declared here.

Screenshot 2024-03-26 221335

Issue with AuthContext

I'm getting this error and cont figure out why...This should be the right way to do it....
Screenshot 2024-01-09 at 18 26 57

No overload matches this call- error

the code i'm using --
password = new FormControl('', [
Validators.required,
hasExclamationMark
]);
but i'm not able to resolve the errors
ang-noMatch error
TS2769: No overload matches this call.
Overload 1 of 5, '(value: string | FormControlState, opts: FormControlOptions, asyncValidator: AsyncValidatorFn | AsyncValidatorFn[]): FormControl<...>', gave the following error.
Type '((control: AbstractControl<any, any>) => ValidationErrors | null)[]' has no properties in common with type 'FormControlOptions'.
Overload 2 of 5, '(value: string | FormControlState, validatorOrOpts?: FormControlOptions | ValidatorFn | ValidatorFn[] | null | undefined, asyncValidator?: AsyncValidatorFn | ... 2 more ... | undefined): FormControl<...>', gave the following error.
Type '(input: FormControl) => { needsExclamation: boolean; } | null' is not assignable to type 'AsyncValidatorFn'.
Types of parameters 'input' and 'control' are incompatible.
Type 'AbstractControl<any, any>' is missing the following properties from type 'FormControl': defaultValue, registerOnChange, registerOnDisabledChange
src/app/app.component.ts:19:13

bug in saved post creator image

In the saved post the creator image is hard coded with current user's profile image which has to be the profile photo of the actual creator of that saved post.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.