trying to run "if" sentence and not working, react - reactjs

I m calling the component like this
<div className="sidebar__chats">
<SidebarChat addNewChat />
i m expecting all avatars except the first one that should say "add new chat". this is the code of the component
function SidebarChat(addNewChat) {
const [seed, setSeed] = useState("");
useEffect(() => {
setSeed(Math.floor(Math.random() * 5000));
}, []);
const createChat = () => {
const roomName = prompt("please enter the name for chat");
if (roomName) {
//do some clever database stuff
}
};
return (
<>
{!addNewChat ? (
<div className="sidebarChat">
<Avatar
alt="João Espinheira"
src={`https://avatars.dicebear.com/api/pixel-art/${seed}.svg`}
sx={{ width: 38, height: 38 }}
/>
<div className="sidebarChat__info">
<h2>room name</h2>
<p>last message...</p>
</div>
</div>
) : (
<div onClick={createChat} className="sidebarChat">
<h2>add new chat</h2>
</div>
)}
</>
);
}
export default SidebarChat;
can anyone help, i think this should work but not entereing the else condition. does anyone knows why? when i dont use the " ! " in the addnewchat every single one turn into avatars, and doesnt do the else statement. i dont understand why cant i use like this, since the code is ok
currently i have this outcome
image1, and it should be something like this image2

Change the first line of the component to
function SidebarChat({addNewChat}) {
The argument to a component is an object containing all the props, so you need to destructure it to access a given prop.

Related

NextJS: some props lost in child component

I created a project using NextJS template Blog starter kit, found here: https://vercel.com/templates/next.js/blog-starter-kit
I've successfully fetched my own posts from a graphql-endpoint and can render them, but when I add values to the post object on my own that weren't included in the original NextJS-project and pass them down to child components, they are available at first but then go undefined and throw an error if I try to use those values.
Please see below code and screenshot of how the values goes from defined to undefined.
I'm new to both Typescript and NextJS but have used React for some time, but I can't grasp why this happens. The code below renders, but I'd like to understand why just some of the props goes undefined, after clearly being included. Also in this specific example I'd like to be able to use coverImage.width in the Image component width-property instead of hardcoding a value.
index.tsx
type Props = {
allPosts: Post[]
}
export default function Index({ allPosts }: Props) {
const heroPost = allPosts[0]
const morePosts = allPosts.slice(1)
return (
<>
<Layout>
<Head>
<title>SWG - Blog</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost heroPost={heroPost} />
)}
{morePosts.length > 0 && <MoreStories posts={morePosts} />}
</Container>
</Layout>
</>
)
}
export const getStaticProps = async () => {
const allPosts = (await getPosts()) || [];
return {
props: { allPosts },
}
}
hero-post.tsx. All heroPost-prop values are available here. Please see below image of console print as well (image link until I have 10 points on SO).
type Props = {
heroPost: {
title: string
coverImage: {
url: string
width: number
height: number
}
date: string
excerpt: string
author: Author
slug: string
}
}
const HeroPost = ({ heroPost }: Props) => {
return (
<section>
<div className="mb-8 md:mb-16">
<CoverImage title={heroPost.title} src={heroPost.coverImage.url} slug={heroPost.slug} coverImage={heroPost.coverImage} />
</div>
<div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<div>
<h3 className="mb-4 text-4xl lg:text-5xl leading-tight">
<Link as={`/posts/${heroPost.slug}`} href="/posts/[slug]">
<a className="hover:underline">{heroPost.title}</a>
</Link>
</h3>
<div className="mb-4 md:mb-0 text-lg">
<DateFormatter dateString={heroPost.date} />
</div>
</div>
<div>
<p className="text-lg leading-relaxed mb-4">{heroPost.excerpt}</p>
<Avatar name={heroPost.author.name} picture={heroPost.author.picture} />
</div>
</div>
</section>
)
}
export default HeroPost
cover-image.tsx. Here's where the props of heroPost goes missing, but only the ones I've declared. Not "src" for example.
type Props = {
title: string
src: string
slug?: string
coverImage: {
url: string
width: number
height: number
}
}
const CoverImage = ({ title, src, slug, coverImage }: Props) => {
console.log(src);
//console.log(title);
console.log(coverImage);
const image = (
<>
<Image src={src} width={1495} height={841} />
</>
)
return (
<div className="sm:mx-0">
{slug ? (
<Link as={`/posts/${slug}`} href="/posts/[slug]">
<a aria-label={title}>{image}</a>
</Link>
) : (
image
)}
</div>
)
}
export default CoverImage
Apparently I can't post images since I'm a new member, but the above console.logs prints like this:
coverImage object exists
prop.src = correct src.value
props.coverImage = cover-image.tsx?0fdc:19 full coverImage object printed
Don't know where these react-devtools-backend lines come from but same thing here, both values exist.
react_devtools_backend.js:4082 correct src.value
react_devtools_backend.js:4082 full coverImage object printed
coverImage then goes undefined
cover-image.tsx?0fdc:19 undefined
but src in props still return its value
cover-image.tsx?0fdc:17 correct src.value
cover-image.tsx?0fdc:19 undefined
same thing with the lines from react_devtools_backend:
react_devtools_backend.js:4082 correct src.value
react_devtools_backend.js:4082 undefined
I've read numerous SO-threads and looked through the NextJS-docs but fail to realise what I'm doing wrong.
console.log of heroPost-object in hero-post component.

Expression statement is not assignment or call when looping through a list and trying to create a grid layout of components

I am trying to create a grid layout of video components but my IDE gives me a warning saying
Expression statement is not assignment or call
import React, {Fragment} from 'react';
import VideoClip from "../Video/VideoClip";
function SubjectView(props) {
let ids = ["RfKHsvF69VdjdMu6bdugsyRcjYpQXrpKd6iZHeEknCkY00",
"RfKHsvF69VdjdMu6bdugsyRcjYpQXrpKd2ipHeEknCkY00",
"RfKHsvF69Vdjdiu6bdugsyRcjYpQXrpKd2iZHeEknCkY00"
];
return (
<Fragment>
<div className="columns-3" >
{ids.map((id)=>{
<VideoClip id={id}/>
console.log(id)
})}
</div>
</Fragment>
);
}
export default SubjectView;
I see the IDs printed in the console but nothing renders.
The video component looks like
function VideoClip() {
let { id } = useParams();
return (
<div className="container mx-auto px-4">
<MuxPlayer
streamType="on-demand"
playbackId={id}
metadata={{
video_id: "video-id-54321",
video_title: "Test video title",
viewer_user_id: "user-id-007",
}}
/>
</div>
);
}
export default VideoClip
I am wondering if I am trying to create the components incorrectly. Is there a best practice when trying to achieve this?
You're not returning any value from ids.map
<>
<div className="columns-3" >
{ids.map((id)=><VideoClip id={id}/>)}
</div>
</>
One issue is you are not returning <VideoClip id={id}/> in map function in jsx. Also, if map is used - key needs to be set
return (
<Fragment>
<div className="columns-3">
{ids.map((id) => {
console.log(id);
return <VideoClip key={id} id={id} />;
})}
</div>
</Fragment>
);
Next issue is about VideoClip component parameter. Id needs to be extracted in that way in case it is passed as an attribute. Also, memoize the objects that you are passing down to a components. Metadata here, for example.
function VideoClip({ id }) {
const metadata = useMemo(() => {
return {
video_id: "video-id-54321",
video_title: "Test video title",
viewer_user_id: "user-id-007"
};
}, []);
return (
<div className="container mx-auto px-4">
<MuxPlayer streamType="on-demand" playbackId={id} metadata={metadata} />
</div>
);
}
Last thing - wrap your array in useMemo so this array will not cause crazy rerenders.
const ids = useMemo(
() => [
"RfKHsvF69VdjdMu6bdugsyRcjYpQXrpKd6iZHeEknCkY00",
"RfKHsvF69VdjdMu6bdugsyRcjYpQXrpKd2ipHeEknCkY00",
"RfKHsvF69Vdjdiu6bdugsyRcjYpQXrpKd2iZHeEknCkY00"
],
[]
);
Note: you will see x2 logs in the console in the Codesandbox due to <StrictMode> is set.

React - Unhandled Rejection (TypeError): Cannot read property 'front_default' of undefined

I'm new to React and I learn best by building my own projects with things that's "fun".
I'm building a Pokedex and everything has been pretty neat, until today when building out a new function.
It's supposed to search every time the user passes in another letter with the "searchPokemon" function.
When this is assigned to the button it works like a charm, but when I try to add it to the "onChange" handler within the input it generates this:
How does that come?
If I assign an invalid pokemon name (string) and then search when the searchPokemon function is assigned to the button it doesn't generate an error message, but now it does?
I assume I need some sort of if statement, but I'm not sure how to go about it.
import Axios from "axios";
import React, { useState } from "react";
import "./SearchPokemon.css";
function PK() {
const api = Axios.create({
baseURL: "https://pokeapi.co/api/v2/",
});
const [pokemonSearched, setPokemonSearched] = useState(false);
const [search, setSearch] = useState("");
const [pokemon, setPokemon] = useState({});
const [pokemonDescription, fetchDescription] = useState({});
const [evolution, pokemonEvolution] = useState({});
const searchPokemon = () => {
api.get(`pokemon/${search}`.toLowerCase()).then((response) => {
setPokemon({
name: response.data.name,
height: response.data.height,
weight: response.data.weight,
img: response.data.sprites.front_default,
id: response.data.id,
type: response.data.types[0].type.name,
type2: response.data.types[1]?.type.name,
});
api.get(`pokemon-species/${response.data.id}/`).then((response) => {
fetchDescription({
entry: response.data.flavor_text_entries[0].flavor_text,
evolution: response.data.evolution_chain.url,
});
api.get(`${response.data.evolution_chain.url}`).then((response) => {
pokemonEvolution({
evolution: response.data.chain.evolves_to[0]?.species.name,
});
});
});
});
setPokemonSearched(true);
};
return (
<div className="page">
<div className="search-section">
<input
placeholder="Search..."
type="text"
onChange={(event) => {
setSearch(event.target.value);
searchPokemon();
}}
/>
<button onClick={searchPokemon}>Click me</button>
</div>
<div className="main">
{!pokemonSearched ? null : (
<>
<h1 style={{ textTransform: "capitalize" }}>{pokemon.name}</h1>
<h1>No. {pokemon.id}</h1>
<img src={pokemon.img} alt="" />
<div className="info-wrapper">
<div className="info">
<h3 style={{ textTransform: "capitalize" }}>
Type: {pokemon.type} {pokemon.type2}
</h3>
<h3>Height: {pokemon.height * 10} Cm</h3>
<h3>Weight: {pokemon.weight / 10} Kg</h3>
</div>
</div>
<div className="desc">
<div className="desc-info">
<h3 style={{ textTransform: "capitalize" }}>
{pokemonDescription.entry}
</h3>
</div>
</div>
</>
)}
</div>
</div>
);
}
export default PK;
The error tells exactly what the problem is!
You cannot read property type of undefined.
So what does that mean? You have on line 23 the following:
type2: response.data.types[1]?.type.name,
As you are using Typescript, so you have to understand what exactly the ? means on that line, which is just you making an assumption that the properties followed by the ? will be present everytime! Even though the typing says otherwise.
But, as you can see in the docs of the pokemon endpoint, types is a list, and some don't have more than 1 type in the array, so you have to figure out a way of checking weather that typing is present to set the state.
Edit: As you are triggering the searchPokemon function on every keyboard stroke (try doing the same here), you are using the hook setPokemon on every response, even when there's no response.data, so here's what causing you trouble, you just need to find a way to validate the response before updating the state.

Unexpected Behavior After State Change in React Component

RenderImages = (): React.ReactElement => {
let selected = this.state.results.filter(x=>this.state.selectedGroups.includes(x.domain))
console.log(selected)
return(
<div className="results_wrapper">
{selected.map((r,i)=>{
let openState = (this.state.selectedImage==i)?true:false;
return(
<RenderPanel panelType={PanelType.large} openState={openState} title={r.domain+'.TheCommonVein.net'} preview={(openIt)=>(
<div className="result" onClick={openIt} style={{ boxShadow: theme.effects.elevation8}}>
<img src={r.url} />
</div>
)} content={(closeIt)=>(
<div className="panel_wrapper">
<div className="panel_content">{r.content}</div>
{this.RenderPostLink(r.domain,r.parent)}
<div onClick={()=>{
closeIt();
this.setState({selectedImage:2})
console.log('wtfff'+this.state.selectedImage)
}
}>Next</div>
<img src={r.url} />
</div>
)}/>
)
})}
</div>
)
}
When I change the state of 'selectedImage', I expect the variable 'openState' to render differently within my map() function. But it does not do anything.
Console.log shows that the state did successfully change.
And what is even stranger, is if I run "this.setState({selectedImage:2})" within componentsDidMount(), then everything renders exactly as expected.
Why is this not responding to my state change?
Update
I have tried setting openState in my component state variable, but this does not help either:
RenderImages = (): React.ReactElement => {
let selected = this.state.results.filter(x=>this.state.selectedGroups.includes(x.domain))
console.log(selected)
let html = selected.map((r,i)=>{
return(
<RenderPanel key={i} panelType={PanelType.large} openState={this.state.openState[i]} title={r.domain+'.TheCommonVein.net'} preview={(openIt)=>(
<div className="result" onClick={openIt} style={{ boxShadow: theme.effects.elevation8}}>
<img src={r.url} />
</div>
)} content={(closeIt)=>(
<div className="panel_wrapper">
<div className="panel_content">{r.content}</div>
{this.RenderPostLink(r.domain,r.parent)}
<div onClick={()=>{
closeIt();
let openState = this.state.openState.map(()=>false)
let index = i+1
openState[index] = true;
this.setState({openState:openState},()=>console.log(this.state.openState[i+1]))
}
}>Next</div>
<img src={r.url} />
</div>
)}/>
)
})
return(
<div className="results_wrapper">
{html}
</div>
)
}
https://codesandbox.io/s/ecstatic-bas-1v3p9?file=/src/Search.tsx
To test, just hit enter at the search box. Then click on 1 of 3 of the results. When you click 'Next', it should close the pane, and open the next one. That is what I'm trying to accomplish here.
#Spitz was on the right path with his answer, though didn't follow through to the full solution.
The issue you are having is that the panel's useBoolean doesn't update it's state based on the openState value passed down.
If you add the following code to panel.tsx, then everything will work as you described:
React.useEffect(()=>{
if(openState){
openPanel()
}else{
dismissPanel();
}
},[openState, openPanel,dismissPanel])
What this is doing is setting up an effect to synchronize the isOpen state in the RenderPanel with the openState that's passed as a prop to the RenderPanel. That way while the panel controls itself for the most part, if the parent changes the openState, it'll update.
Working sandbox
I believe it's because you set openState in your map function, after it has already run. I understand you think the function should rerender and then the loop will run once more, but I think you'll need to set openState in a function outside of render.
The problem is that even though you can access this.state from the component, which is a member of a class component, there's nothing that would make the component re-render. Making components inside other components is an anti-pattern and produces unexpected effects - as you've seen.
The solution here is to either move RenderImages into a separate component altogether and pass required data via props or context, or turn it into a normal function and call it as a function in the parent component's render().
The latter would mean instead of <RenderImages/>, you'd do this.RenderImages(). And also since it's not a component anymore but just a function that returns JSX, I'd probably rename it to renderImages.
I tire to look at it again and again, but couldn't wrap my head around why it wasn't working with any clean approach.
That being said, I was able to make it work with a "hack", that is to explicitly call openIt method for selectedImage after rendering is completed.
RenderImages = (): React.ReactElement => {
let selected = this.state.results.filter((x) =>
this.state.selectedGroups.includes(x.domain)
);
return (
<div className="results_wrapper">
{selected.map((r, i) => {
let openState = this.state.selectedImage === i ? true : false;
return (
<RenderPanel
key={i}
panelType={PanelType.medium}
openState={openState}
title={r.domain + ".TheCommonVein.net"}
preview={(openIt) => {
/* This is where I am making explicit call */
if (openState) {
setTimeout(() => openIt());
}
/* changes end */
return (
<div
className="result"
onClick={openIt}
style={{ boxShadow: theme.effects.elevation8 }}
>
<img src={r.url} />
</div>
);
}}
content={(closeIt) => (
<div className="panel_wrapper">
<div className="panel_content">{r.content}</div>
{this.RenderPostLink(r.domain, r.parent)}
<div
onClick={() => {
closeIt();
this.setState({
selectedImage: i + 1
});
}}
>
[Next>>]
</div>
<img src={r.url} />
</div>
)}
/>
);
})}
</div>
);
};
take a look at this codesandbox.

React redux saga multiple renders

I'm new to react and I'm having an issue of multiple renders and I was just wondering if I'm doing this right, so I dispatched an action to get a note list, in my list component which looks like this for now :
import React, {useState, useEffect} from 'react';
export default function NoteList (props){
const [ noteList, updateNoteList ] = useState([]);
useEffect(()=>{
updateNoteList(
props.noteList.map(note => {
return {...note, mode : 'title-mode'};
})
)
},[props.noteList])
console.log(noteList);
return (
<div>
Notes come here
</div>
)
}
this component is connected in another container class but that's irrelevant, so what happens is this component renders 4 times, two times without the useEffect hook and two more with it, what I want to achieve is I need to add an item in the object of each note (which is mode : title-mode) in a state for this component which works fine with this code, as to why I'm adding this mode in a state is that I want to change this inside the note array so I can change the view mode for each note , but this component renders 4 times as I mentioned, and in my head no way that this is the correct way to do this.
Please help if you have the time .
We could achieve the display of the notes list by making a display-mode state in the <Note /> component it self so changing the mode won't affect other notes and this way we won't have extra re-renders, also using this approach will allow also modifying the note locally without dispatching it to the store then we could update the store at the end gaining in perfs.
So basically this is the approach (codesandbox):
const Note = ({ title, content }) => {
const [isExpanded, setIsExpanded] = useState(false);
return (
<div
style={{ border: "1px solid", margin: 5 }}
onClick={() => setIsExpanded(!isExpanded)}
>
{!isExpanded ? (
<div>
<h2>{title}</h2>
</div>
) : (
<div>
<h2>{title}</h2>
<p>{content}</p>
</div>
)}
</div>
);
};
function App() {
// this is the notes state, it could be coming from redux store so
// we could interact with it (modifying it if we need)
const [notes, setNotes] = React.useState([
{ id: 1, title: "note 1", content: "this is note 1" },
{ id: 2, title: "note 2", content: "this is note 2" }
]);
return (
<div className="App">
{notes.map((note) => (
<Note key={note.id} {...note} />
))}
</div>
);
}

Resources