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 344.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 Issues

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

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

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?

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

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!!!

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

Post Details Class Error

PostDetails.jsx @ d044bd9
Line 106 has:

className={`ost_details-delete_btn ...

This should be:

className={`post_details-delete_btn ...

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

Sigin Signup Not working

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

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.

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

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

@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...

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);

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

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]

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

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.

"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.

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('/');
  };

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

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"]

License

What is the license for the code and the assets?

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

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!

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

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! :)

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.