I have a list of data from graphql I am returning in from a service folder and referencing it in an index file, but for some unknown reason these data are not being fetched as I keep getting the error Cannot read properties of undefined (reading 'url') when I try to fetch a featured image and even after I comment the image line out, I get an empty result. I haven't spotted any error so please help me figure out what I may be doing wrong with the following code below
services/index.js
export const getBlogPosts = async () => {
const query = gql `
query MyQuery {
blogPostsConnection {
edges {
node {
title
slug
excerpt
createdAt
featuredImage {
url
}
blogcategories {
name
slug
}
blogTags {
name
slug
}
}
}
}
}
`
const results = await request(graphqlAPI, query)
return results.blogPostsConnection.edges
}
pages/blog.jsx
import React, {useState, useEffect} from 'react'
import {getBlogPosts} from '../services'
import {GiTimeBomb} from 'react-icons/gi'
import moment from 'moment'
const Home = () => {
const [blogposts, setBlogPosts] = useState([]);
useEffect(() => {
getBlogPosts().then((result) => {
setBlogPosts(result);
});
}, []);
return (
<div>
{blogposts.map((blogpost) => (
<div className="bg-white shadow-sm rounded-sm" key={blogpost.slug} blogpost={blogpost.node}>
<a href="#" className="overflow-hidden block">
<img src={blogpost.featuredImage.url} alt='no'className="w-full h-96 object-cover transform hover:scale-110 transition duration-500" />
</a>
<div className="p-4">
<a href="#">
<h2 className="text-2xl font-semibold text-gray-700 hover:text-blue-500 transition">{blogpost.title}</h2>
</a>
<p className="text-gray-500 text-sm mt-2">{blogpost.excerpt}</p>
<div className="flex mt-3 space-x-5">
<div className="flex items-center text-gray-400 text-sm">
<span className="mr-2 text-sx">
<i><AiOutlineUser /></i>
</span>
Kimmoramicky
</div>
<div className="flex items-center text-gray-400 text-sm">
<i className='pr-1 text-xs'><GiTimeBomb /></i>
<span>{moment(blogpost.createdAt).format('MMM DD, YYYY')}</span>
</div>
</div>
<div className='mt-4'>
Read more...
</div>
</div>
</div>
))}
</div>
)
}
export default Home
Related
I am setting up a login page using google OAuth in react, I am following a youtube tutorial, everything seems to work fine but somehow after logging in, I am not being redirected to my homepage. here is the code (Login.jsx):
import React from 'react'
import GoogleLogin from 'react-google-login';
import { useNavigate } from 'react-router-dom';
import { FcGoogle } from 'react-icons/fc';
import carVideo from '../assets/car.mp4';
import logo from '../assets/speedograph white.png';
import { client } from '../client';
const Login = () => {
const navigate = useNavigate();
const responseGoogle = (response) => {
localStorage.setItem('user', JSON.stringify(response.profileObj));
if (response.profileObj) {
const { name, googleId, imageUrl } = response.profileObj;
const doc = {
_id: googleId,
_type: 'user',
userName: name,
image: imageUrl,
};
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={carVideo}
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 ml-3">
<img src={logo} width="130px" alt="logo" />
</div>
<div className='shadow-2xl'>
<GoogleLogin
clientId={process.env.REACT_APP_GOOGLE_API_TOKEN}
render={(renderProps) => (
<button
type='button'
className='bg-white flex justify-center items-center p-3 rounded-lg cursor-pointer outline-none'
onClick={renderProps.onClick}
disabled={renderProps.disabled}
>
<FcGoogle className='mr-4' />Sign in with Google
</button>
)}
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy="single_host_origin"
/>
</div>
</div>
</div>
</div>
)
}
export default Login
I think the problem is due to the if condition, but I added it after reviewing a Stackoverflow tab that suggested adding it as a null check, before adding it I was getting the error:
Cannot destructure property 'name' of 'response.profileObj'
now the error is gone but it is not redirecting me to the home page (neither did it do so before the error). So where am I missing in my code exactly?
Error:
./src/components/Main.jsx 26:12
Module parse failed: Unexpected token (26:12)
You may need an appropriate loader to handle this file type.
|
| var turncateString = function turncateString(str, num) {
if (str?.length > num) {
| return str.slice(0, num) + '....';
| } else {
Code:
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import requests from "../Requests";
import axios from "axios";
const Main = () => {
const [movies, setMovies] = useState([]);
const movie = movies[Math.floor(Math.random() * movies.length)];
useEffect(() => {
axios.get(requests.requestPopular).then((response) => {
setMovies(response.data.results);
});
}, []);
// console.log(movie)
const turncateString = (str, num) => {
if (str?.length > num) {
return str.slice(0, num) + "....";
} else {
return str;
}
};
return (
<div className="w-full h-[550px] text-white">
<div className="w-full h-full">
<div className="absolute w-full h-[550px] bg-gradient-to-r from-black"></div>
<img
className="w-full h-full object-cover"
src={`https://image.tmdb.org/t/p/original/${movie?.backdrop_path}`}
alt={movie?.title}
/>
<div className="absolute w-full top-[40%] p-4 md:p-8">
<h1 className="text-3xl md:text-5xl font-bold">{movie?.title}</h1>
<div className="my-4">
<button className="border bg-gray-300 text-black border-gray-300 py-2 px-5">
Play
</button>
<button className="border text-gray-300 border-gray-300 py-2 px-5 ml-4">
Watch Later
</button>
</div>
<p className="text-gray-400 text-sm">
Released: {movie?.release_date}
</p>
<p className="w-full md:max-w-[70%] lg:max-w-[50%] xl:max-w-[35%] text-gray-200">
{turncateString(movie?.overview, 150)}
</p>
</div>
</div>
</div>
);
};
export default Main;
enter code here
Can anyone help me resolve this error?
error I'm getting: TypeError: Cannot read properties of undefined (reading 'replaceAll')
problem line: {user.userName.replaceAll(' ', '')}
i tried changing removing the replaceAll method since it wasn't a huge deal but the same error remained. I also tried writing it like as a regex but no luck:
{user.userName.replace(/\s+/g, '')}{' '}
Here's the all the code:
import React, { useEffect } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { GoVerified } from 'react-icons/go';
import useAuthStore from '../store/authStore';
import { IUser } from '../types';
const SuggestedAccounts = () => {
const { fetchAllUsers, allUsers } = useAuthStore();
useEffect(() => {
fetchAllUsers();
}, [fetchAllUsers]);
return (
<div className="xl:border-b-2 border-gray-200 pb-4">
<p className="text-gray-500 font-semibold m-3 mt-4 hidden: xl:block">
Suggested Accounts
</p>
<div>
{allUsers.slice(0, 6).map((user: IUser) => (
<Link href={`/profile/${user._id}`} key={user._id}>
<div className="flex gap-3 hover:bg-primary p-2 cursor-pointer font-semibold rounded">
<div className="w-8 h-8">
<Image
src={user.image}
width={34}
height={34}
className="rounded-full"
alt="user profile"
layout="responsive"
/>
</div>
<div className="hidden xl:block">
<p className="flex gap-1 items-center text-md font-bold text-primary lowercase">
{user.userName.replaceAll(' ', '')}
<GoVerified className="text-blue-400" />
</p>
<p className="capitalize text-gray-400 text-xs">
{user.userName}
</p>
</div>
</div>
</Link>
))}
</div>
</div>
);
};
export default SuggestedAccounts;
I get the error "Uncaught TypeError: DroppedItem.map is not a function ReactJS" when trying to show a floating window on my page after opening a case. I think it has something to do with renders (https://jsramblings.com/are-you-logging-the-state-immediately-after-updating-it-heres-why-that-doesnt-work/) but I got no idea how to fix it. Please help. I use Axios to load arrays from my backend server. The "className" is from TailWind.
import {useEffect, useState, useContext} from "react"
import {useLocation} from 'react-router-dom'
import Axios from "axios";
import { AppContext } from "/src/App";
export default function CaseDetail(){
const [ContentList, setContentList] = useState([])
const [Case, setCase] = useState([])
const [ShowDrop, setShowDrop] = useState(false)
const [DroppedItem, setDroppedItem] = useState([])
const { token } = useContext(AppContext);
const { setToken } = useContext(AppContext);
const { userID } = useContext(AppContext);
const DroppedItemFunc = (array) => {
setDroppedItem(array)
}
const DropWindow = () => {
setShowDrop(!ShowDrop)
}
const MilSpecList = ContentList.filter(function(driver){
return driver.RarityName === "Mil-Spec"
})
const openCase = (CasePrice) => {
const Price = parseInt(CasePrice)
if (token >= Price){
setToken(token-Price)
const randomNumero = Math.random()* 100;
if(randomNumero <= 70)
{
const millength = MilSpecList.length
const randomItemM = Math.floor(Math.random() * (millength - 0)+ 0)
console.log(MilSpecList[randomItemM].SkinName)
console.log(MilSpecList[randomItemM].IDItem)
submitItem(MilSpecList[randomItemM].IDItem)
setDroppedItem(MilSpecList[randomItemM])
setShowDrop(!ShowDrop)
}
}else{console.log("No funds")}
}
return(
<div className="flex justify-center align-bottom">
{ShowDrop && <div className=" absolute">
{DroppedItem.map(item => (
<div className=" border-2 border-slate-500 w-[25rem] h-[30rem] p-1.5 px-2 m-2 box-content rounded-cool bg-slate-700 ">
<button
className=' border-2 border-green-700 bg-green-400 hover:bg-green-600 text-green-900 hover:text-rose-50 w-[100%] h-10 rounded-cool '
onClick={()=>{DropWindow()}}
>
Close
</button>
</div>
))}
</div>
}
<div className="bg-slate-800 rounded-cool text-white divide-y-2 w-3/5 p-3">
{Case.map(item => (
<h1 key={item.CaseName} className="text-4xl font-bold text-slate-200 py-2" >
{item.CaseName} 💼
</h1>
))}
{Case.map(item => (
<div key={item.CaseName} className="flex justify-center p-3 mt-2">
<div className=" w-[50%] p-1.5 px-2 m-2 box-content rounded-cool bg-slate-700 "
>
<div className="flex justify-center">
<img className="" src={`src/images/${item.CaseImage}`}/>
</div>
<h1 className="hover:text-orange-300">
{item.CaseName}
</h1>
<h1 className="hover:text-orange-300 basis-1/2">
{item.CasePrice} Tokens
</h1>
<div className=" flex justify-center">
<button className=" cursor-pointer text-xl text-slate-900 w-40 h-10 hover:text-orange-300 hover:bg-slate-600 hover:border-2 hover:border-white-200 bg-orange-300 rounded-cool px-2 py-0.25 transition-all"
onClick={() => {openCase(item.CasePrice)}}
>
OPEN
</button>
</div>
</div>
</div>
))}
</div>
</div>
)
}
your error is here: setDroppedItem(MilSpecList[randomItemM]) - you cannot modify the data type of your state from an array, to some other value, as the method 'map' no longer becomes available. Try to make sure you do not modify data structures, I find that prop-types (when in reactJS), typescript (when in reactTS), and eslint (in general) help me a lot to make sure I don't accidentally mutate my structure type on accident. Try also console logging the value and type of MilSpecList[randomItemM] to confirm the type is indeed an array, as well as anywhere you might be running setDroppedItem
I'm using react with sanity io to create a portfolio page. I would like to create an unordered list according to how many tags I have a on a project. A project is composed of a title, image, description, and tags(this is just an array).
What I have tried is:
{project.tags.map(type => {
return (
<li>{type.type.name}</li>
)
})}
And I keep getting the error: "TypeError: project.forEach is not a function". If I just render
{project.tags}
all of the tags are displayed but then I can't style them hence the need to put them into a list.
Does anyone know how to accomplish this?
import React, { useEffect, useState} from "react";
import sanityClient from "../client.js";
import '../index.css';
export default function Project() {
const [projectData, setProjectData] = useState(null);
useEffect(() => {
sanityClient.fetch(`*[_type == "project"] | order(index) {
title,
mainImage{
asset->{
_id,
url
},
},
description,
projectType,
link,
tags
}`).then((data) => setProjectData(data)).catch(console.error);
}, []);
return (
<div className="antialiased text-gray-800 bg-gray-400">
<div className="container relative flex flex-col px-6 mx-auto space-y-8">
<div className="absolute inset-0 z-0 w-2 h-full bg-white shadow-md left-38 md:mx-auto md:right-0 md:left-0"></div>
{projectData && projectData.map((project, index)=> (
<div className="relative z-10 p-10 ">
<img src={project.mainImage.asset.url} alt={project.mainImage.alt} className="timeline-img" />
<div className={`${index % 2 === 0 ? "timeline-container-left timeline-container" : "timeline-container" }`} >
<p className="font-bold uppercase">{project.title}</p>
<div className={`${index % 2 === 0 ? "timeline-pointer-left timeline-pointer" : "timeline-pointer" }`} aria-hidden="true"></div>
<div className="p-6 bg-white rounded-md shadow-md sm:p-2">
<p className="pt-1">{project.description}</p>
</div>
</div>
</div>
))}
</div>
</div>
)
}
{project.tags.map( type => ( {type} ))} is the answer.