Code Monkey home page Code Monkey logo

project_shareme_social_media's Introduction

project_shareme_social_media's People

Contributors

adrianhajdin avatar kiranism avatar

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

project_shareme_social_media's Issues

App flashes and disappears after login

After I signed in, the app goes to the home page but then the content disappears after a few seconds. On checking the dom tree in the dev tools, the root div is emptied after the app loads.

Fixed items order in cart

Hi,
I have come up with a very simple solution to get a fixed order of the products in the cart.

The only thing we have to do, is to order the array before setting the useState variable. The only 2 functions to change are: onAdd and toggleCartItemQuantity.

Be careful, because toggleCartItemQuantity is badly written in the original code, and here in my solution I have corrected it.

const onAdd = (product, quantity) => {
  const checkProductInCart = cartItems.find((item) => item._id === product._id);
  
  setTotalPrice((prevTotalPrice) => prevTotalPrice + product.price * quantity);
  setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity);
  
  if (checkProductInCart) {
    const updatedCartItems = cartItems.map((cartProduct) => {
      if (cartProduct._id === product._id)
        return {
          ...cartProduct,
          quantity: cartProduct.quantity + quantity,
        };
    });
  
    setCartItems(updatedCartItems);
  } else {
    product.quantity = quantity;
    // Sort the items to avoid them moving in the cart
    const sortedItems = [...cartItems, { ...product }];
    sortedItems.sort((a, b) => {
      const nameA = a.name.toUpperCase(); // ignore upper and lowercase
      const nameB = b.name.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }
      // names must be equal
      return 0;
    });
    setCartItems(sortedItems);
  }
  
  toast.success(`${qty} ${product.name} added to the cart.`);
};

const toggleCartItemQuantity = (id, value) => {
  foundProduct = cartItems.find((item) => item._id === id);
  // index = cartItems.findIndex((product) => product._id === id);
  const newCartItems = cartItems.filter((item) => item._id !== id);
  
  if (value === "inc") {
    // Sort the items to avoid them moving in the cart
    const sortedItems = [
      ...newCartItems,
      { ...foundProduct, quantity: foundProduct.quantity + 1 },
    ];
    sortedItems.sort((a, b) => {
      const nameA = a.name.toUpperCase(); // ignore upper and lowercase
      const nameB = b.name.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }
      // names must be equal
      return 0;
    });
    setCartItems(sortedItems);
    setTotalPrice((prevTotalPrice) => prevTotalPrice + foundProduct.price);
    setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + 1);
  } else if (value === "dec") {
    if (foundProduct.quantity > 1) {
      // Sort the items to avoid them moving in the cart
      const sortedItems = [
        ...newCartItems,
        { ...foundProduct, quantity: foundProduct.quantity - 1 },
      ];
      sortedItems.sort((a, b) => {
        const nameA = a.name.toUpperCase(); // ignore upper and lowercase
        const nameB = b.name.toUpperCase(); // ignore upper and lowercase
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }
        // names must be equal
        return 0;
      });
      setCartItems(sortedItems);
      setTotalPrice((prevTotalPrice) => prevTotalPrice - foundProduct.price);
      setTotalQuantities((prevTotalQuantities) => prevTotalQuantities - 1);
    }
  }
};

secure the sign on

Is it safe practice to safe the google Id to local storage. I am trying to learn the best way to have memberships that are secure. Everywhere online says something else...

Solution for google OAuth new update

I have a functional template of your code with the new standard of implementing OAuth and decoding it with jwt. I would love to contribute if you give me the option.

Solution for -> popup closed by user error during the authentication

According to new 2022 update you have to do following steps :

  1. npm i gapi-script

  2. In login.jsx add ->
    import { gapi } from "gapi-script";

  3. And at last add this code before function responseGoogle

window.gapi.load('client:auth2', () => { window.gapi.client.init({ clientId: ${process.env.REACT_APP_GOOGLE_API_TOKEN}, plugin_name: "chat" })})

Unsave Post

Can someone suggest how to unSave a post by re-clicking the save button?

error

  • But the above method somehow is not working as expected. The pin is not getting Unsaved. Any Help Would be highly Appreciated๐Ÿ™‚
    Animation

  • My Project in Github

Images

Images are not showing when clicked on specific category and saying no pins available

Content disappeared after login

When i successfully log in with google account it redirects me to homepage and shows a loading screen but after few seconds the whole screen becomes white

"Uncaught TypeError: Cannot destructure property 'name' of 'response.profileObj" - Solution

Solution for errors such as: "Uncaught TypeError: Cannot destructure property 'name' of 'response.profileObj' as it is undefined."
and sanity database not updating or redirects to home failing.

Here's how I solved it:

  1. Install the latest Google OAuth Package: npm install @react-oauth/google and get your client ID as shown in JSM's video.
  2. Install the dependency jwt-decode: npm install jwt-decode. This is to decode the jwt_token that the google oauth returns.
  3. Replace your login.jsx with the following:
import React from 'react';
import {GoogleLogin, GoogleOAuthProvider} from '@react-oauth/google';
import { useNavigate } from 'react-router-dom';
import shareVideo from '../assets/share.mp4';
import logo from '../assets/logowhite.png';
import { client } from '../client';
import jwt_decode from 'jwt-decode'

const Login = () => {
    const navigate = useNavigate();

    const responseGoogle = (response) => {

        const userResponse = jwt_decode(response.credential);

        localStorage.setItem('user', JSON.stringify(userResponse));
        const { name, sub, picture } = userResponse;

        const doc = {
            _id: sub,
            _type: 'user',
            userName: name,
            image: picture
        }
        
        client.createIfNotExists(doc).then(()=>{
            navigate('/', {replace: true})
        });

    };

    return (
        <div className="flex justify-start items-center flex-col h-screen">
            <div className=" relative w-full h-full">
                <video
                    src={shareVideo}
                    type="video/mp4"
                    loop
                    controls={false}
                    muted
                    autoPlay
                    className="w-full h-full object-cover"
                />

                <div className="absolute flex flex-col justify-center items-center top-0 right-0 left-0 bottom-0    bg-blackOverlay">
                    <div className="p-5">
                        <img src={logo} width="130px" alt='logo' />
                    </div>

                    <GoogleOAuthProvider
                        clientId={`${process.env.REACT_APP_GOOGLE_OAUTH_CLIENT_ID}`} className="shadow-2xl">
                        <GoogleLogin
                            onSuccess={responseGoogle}
                            onFailure={responseGoogle}
                            cookiePolicy="single_host_origin"
                        />
                    </GoogleOAuthProvider>
                </div>
            </div>
        </div>
    );
};

export default Login;
  1. To solve the images not appearing issue, as well as redirecting issues, replace Home.jsx with this:
import React, { useState, useRef, useEffect } from 'react'
import { HiMenu } from 'react-icons/hi'
import { AiFillCloseCircle } from 'react-icons/ai'
import { Routes, Route, Link } from 'react-router-dom'
import { Sidebar, UserProfile } from '../components'
import { client } from '../client'
import logo from '../assets/logo.png'
import Pins from './Pins'
import { userQuery } from '../utils/data'

const Home = () => {
  const [user, setUser] = useState(null)
  const [toggleSidebar, setToggleSidebar] = useState(false)
  
  const scrollRef = useRef(null);

  const userInfo = localStorage.getItem('user') !== 'undefined' ? JSON.parse(localStorage.getItem('user')) : localStorage.clear();

  useEffect(() => {
    const query = userQuery(userInfo?.sub);

    client.fetch(query).then((data) => {
      setUser(data[0]);
    })
    //eslint-disable-next-line
  }, []);

  useEffect(() => {
    scrollRef.current.scrollTo(0, 0);
  });

  return (
    <div className="flex bg-gray-50 md:flex-row flex-col h-screen transition-height duration-75 ease-out">
      <div className="hidden md:flex h-screen flex-initial">
        <Sidebar user={user && user} />
      </div>
      <div className="flex md:hidden flex-row">
        <div className="p-2 w-full flex flex-row justify-between items-center shadow-md">
          <HiMenu fontSize={40} className="cursor-pointer" onClick={() => setToggleSidebar(true)} />
          <Link to="/">
            <img src={logo} alt="logo" className="w-28" />
          </Link>
          <Link to={`user-profile/${user?._id}`}>
            <img src={user?.image} alt={user?.name} className="w-9 h-9 rounded-full " />
          </Link>
        </div>
        {toggleSidebar && (
          <div className="fixed w-4/5 bg-white h-screen overflow-y-auto shadow-md z-10 animate-slide-in">
            <div className="absolute w-full flex justify-end items-center p-2">
              <AiFillCloseCircle fontSize={30} className="cursor-pointer" onClick={() => setToggleSidebar(false)} />
            </div>
            <Sidebar closeToggle={setToggleSidebar} user={user && user} />
          </div>
        )}
      </div>
      <div className="pb-2 flex-1 h-screen overflow-y-scroll" ref={scrollRef}>
        <Routes>
          <Route path="/user-profile/:userId" element={<UserProfile />} />
          <Route path="/*" element={<Pins user={user && user} />} />
        </Routes>
      </div>
    </div>
  )
}

export default Home

Side Note: Don't forget to wrap your env variables in this: {`${MY-ENV-VARIABLE}`}

Also, this solves the problem for these two components (login and home), but for the other components, some changes will have to be made. I will post these changes as soon as I am done with the project.

Actions take a while

Hi, I was wondering if someone could clear this up for me.

Some actions take a while to execute and do not become instantly apparent after the auto-reload when doing something

For example:

  • Saving posts requires a few manual refreshes before it is shown that a post is saved
  • When making or deleting a post I sometimes need to refresh more than a few times before anything shows up or disappears
  • Comments take time to show after being posted

Is this normal? I'd assume it takes time for the frontend and the Sanity client to communicate with each other and for Sanity to reflect and confirm these changes.
Or could it potentially be something in my code that I could fix to speed up this process?

Google Log In

I have encountered with,

"'Invalid cookiePolicy"
"gapi.auth2.ExternallyVisibleError: Invalid cookiePolicy\n"

Cross-Origin-Opener-Policy error with Google Login

Hi!

After creating the API key and inserting it into the project, when I open the popup window and log in, it gives me the following console errors and does not return any data, please, could you help me?

image

Icon is not transparent

The icon/favicon for your app is not transparent, if you would like, @adrianhajdin , I can find another one, or make this one transparent. Thank you.

to this:

cam

delay when taking any action

So, when i do anything (Adding a new pin, saving a pin, writing a comment, Deleting a pin), The sanity database register the action instantly

However, the change doesn't appear in the front end for about 3-5 minutes after the change has already been done, that can lead into some issues like being able to click the save button 5 or 6 times and sanity will register it every time and by the time the button changes there's 6 saves while it's only been one user who just spammed the button until the front end was updated

Uh ohโ€ฆ found errors in schema

pin document > fields > save array > of > <unnamed_type_@_index_0> save

Unknown type: save. Did you mean "date"? Valid types are: user, pin, postedBy, array, block, boolean, datetime, date, document, email, file, geopoint, image, number, object, reference, crossDatasetReference, slug, string, telephone, text and url

pin document > fields > comment array > of > <unnamed_type_@_index_0> comment

Unknown type: comment. Valid types are: user, pin, postedBy, array, block, boolean, datetime, date, document, email, file, geopoint, image, number, object, reference, crossDatasetReference, slug, string, telephone, text and url

<unnamed_type_@_index_3>

  • Invalid/undefined type declaration, check declaration or the import/export of the schema type.
  • Type is missing a type. Valid types are: user, pin, postedBy, array, block, boolean, datetime, date, document, email, file, geopoint, image, number, object, reference, crossDatasetReference, slug, string, telephone, text and url

<unnamed_type_@_index_4>

  • Invalid/undefined type declaration, check declaration or the import/export of the schema type.
  • Type is missing a type. Valid types are: user, pin, postedBy, array, block, boolean, datetime, date, document, email, file, geopoint, image, number, object, reference, crossDatasetReference, slug, string, telephone, text and url

cannot switch active home sidebar

I have tried a lot of times to switch the Home sidebar but it always shows active on the other hand all other sidebar switches nicely. Anyone help to figure me it out? Here is my GitHub code link share-me
image

`
import { NavLink, Link } from 'react-router-dom';
import { RiHomeFill } from 'react-icons/ri';
import { IoIosArrowForward } from 'react-icons/io';

import logo from '../assets/logo.png';

const categories = [
{ name: 'Animals' },
{ name: 'Wallpapers' },
{ name: 'Photography' },
{ name: 'Gaming' },
{ name: 'Coding' },
{ name: 'Other' },
];

const isNotActiveStyle =
'flex items-center px-5 gap-3 text-gray-500 hover:text-black transition-all duration-200 ease-in-out capitalize';

const isActiveStyle =
'flex items-center px-5 gap-3 font-extrabold border-r-2 border-black transition-all duration-200 ease-in-out capitalize';

const Sidebar = ({ user, closeToggle }) => {
const handleCloseSidebar = () => {
if (closeToggle) closeToggle(false);
};

return (
	<div className="flex flex-col justify-between bg-white h-full overflow-y-scroll min-w-210 hide-scrollbar">
		<div className="flex flex-col">
			<Link
				to="/"
				className="flex px-5 gap-2 my-6 pt-1 w-190 items-center"
				onClick={handleCloseSidebar}
			>
				<img src={logo} alt="logo" className="w-full" />
			</Link>
			<div className="flex flex-col gap-5">
				<NavLink
					to="/"
					className={({ isActive }) =>
						isActive ? isActiveStyle : isNotActiveStyle
					}
					onClick={handleCloseSidebar}
				>
					<RiHomeFill />
					Home
				</NavLink>
				<h3 className="mt-2 px-5 text-base 2xl:text:xl">
					Discover categories
				</h3>
				{categories.slice(0, categories.length - 1).map((category) => {
					return (
						<NavLink
							to={`/category/${category.name}`}
							className={({ isActive }) =>
								isActive ? isActiveStyle : isNotActiveStyle
							}
							onClick={handleCloseSidebar}
							key={category.name}
						>
							{category.name}
						</NavLink>
					);
				})}
			</div>
		</div>
		{user && (
			<Link
				to={`user-profile/${user._id}`}
				className="flex my-5 mb-3 gap-2 p-2 items-center bg-white rounded-lg shadow-lg mx-3"
				onClick={handleCloseSidebar}
			>
				<img
					src={user.image}
					className="w-10 h-10 rounded-full"
					alt="user-profile"
				/>
				<p>{user.userName}</p>
				<IoIosArrowForward />
			</Link>
		)}
	</div>
);

};

export default Sidebar;

`

Can't load logo because of user info fetch's user as undefined

data.js

`export const userQuery = (userId) => { const query = `*[_type == "user" && _id == '${userId}']`; return query; };`

Home.jsx

`import React, { useState, useRef, useEffect } from 'react'; import { HiMenu } from 'react-icons/hi'; import { AiFillCloseCircle } from 'react-icons/ai'; import { Link, Route, Routes } from 'react-router-dom';

import { Sidebar, UserProfile } from '../components';
import Pins from './Pins';
import { userQuery } from '../utils/data';
import { client } from '../client';
import logo from '../assets/logo.png';

const Home = () => {
const [toogleSidebar, setToogleSidebar] = useState(false);
const [user, setUser] = useState(null);
const userInfo =
localStorage.getItem('user') !== 'undefined'
? JSON.parse(localStorage.getItem('user'))
: localStorage.clear();
useEffect(() => {
const query = userQuery(userInfo?.googleId);
console.log(query);
client.fetch(query).then((data) => {
console.log(data[0]);
setUser(data[0]);
});
}, []);
return (






<HiMenu
fontSize={40}
className='cursor-pointer'
onClick={() => setToogleSidebar(false)}
/>

logo

<Link to={user-profile/${user?._id}}>
logo



);
};

export default Home;`

Issue in mobile View screen

While checking mobile view not seeing delete,download saved button on pins
does anyone have any idea what is wrong?

Can't import the named export 'jsonRequest' from non EcmaScript module (only default export is available)

Hello i am receiving this error:


./node_modules/@sanity/client/dist/sanityClient.browser.mjs
Can't import the named export 'jsonRequest' from non EcmaScript module (only default export is available)

here is my client.js:


import SanityClient from '@sanity/client';
import imageUrlBuilder from '@sanity/image-url';

export const client = SanityClient({
    projectId: process.env.REACT_APP_SANITY_PROJECT_ID,
    dataset: 'production',
    apiVersion:'2021-10-21',
    useCdn: false,
    token: process.env.NEXT_PUBLIC_SANITY_TOKEN,
});

const builder = imageUrlBuilder(client);

export const urlFor = (source) => builder.image(source);


whenever this export is imported in any file i get this error.

import {client} from '../client'

i have tried sanityClient, SanityClient and createClient all resulting in the same issue.

finally here is my package.json and a screenshot of the manager on sanity:

{
  "name": "excuse_frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@react-oauth/google": "^0.7.0",
    "@sanity/client": "^4.0.1",
    "@sanity/image-url": "^1.0.2",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.3.3",
    "jwt-decode": "^3.1.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.7.1",
    "react-loader-spinner": "^5.3.4",
    "react-masonry-css": "^1.0.16",
    "react-router-dom": "^6.8.1",
    "react-scripts": "^2.1.3",
    "uuid": "^9.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "tailwindcss": "^3.2.6"
  }
}

Screenshot 2023-02-14 at 3 43 54 AM

Any solutions? I can't find any proper solutions online.
Much appreciated.

Uncaught TypeError: Cannot read properties of undefined (reading 'name')

Amazing content. Best tut out there, and I followed it to the T (even cloned the repo) and I am still getting an error when signing into Google on the production build on a production site. This is what I see in the console: " Uncaught TypeError: Cannot read properties of undefined (reading 'name') " .

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.