React console.log not showing array values - reactjs

Console it printing Array [] instead of values. I have checked the code but figure it out. Why doesn't console.log show me array values when i click button?
import React from "react";
import { StyleSheet, View, FlatList } from "react-native";
import DataManager from "../config/DataManager";
const getMemories = () => {
let commonData = DataManager.getInstance();
let user = commonData.getUserID();
return commonData.getMemories(user);
}
function MemoriesScreen(props) {
const memoryList = getMemories();
console.log(memoryList);
return (
<AppScreen style={styles.container}>
<FlatList
data={memoryList}
keyExtractor = {memory => memory.memoryid.toString()}
renderItem = {({item}) =>
<AppCard
title={item.title}
subtitle={item.subtitle}
image={item.image}
category={item.category}
/>}
/>
</AppScreen>
);
}
const styles = StyleSheet.create({
container:{
backgroundColor:AppColors.otherColor,
flex:1,
marginTop:0,
},
})
export default MemoriesScreen;
this the DataManger js screen
export default class DataManager {
static myInstance = null;
userID = "";
memories = [
{
userid: "user1",
memoryid: 1,
title: "Memories of School days",
subtitle: "Created on 3rd of January, 2005",
image: require("../assets/School-days.jpeg"),
category: "Childhood",
},
{
userid: "user1",
memoryid: 2,
title: "Memories of School days",
subtitle: "Created on 3rd of January, 2005",
image: require("../assets/School-days.jpeg"),
category: "Childhood",
},
{
userid: "user2",
memoryid: 1,
title: "Memories of School days",
subtitle: "Created on 3rd of January, 2005",
image: require("../assets/School-days.jpeg"),
category: "Childhood",
}
];
static getInstance() {
if (DataManager.myInstance == null) {
DataManager.myInstance = new DataManager();
}
return this.myInstance;
}
getUserID() {
return this.userID;
}
setUserID(id) {
this.userID = id;
}
getMemories(id) {
return this.memories.filter((memory) => memory.userid === id);
}
addMemory(memory){
this.memories.push(memory);
}
}

Your array can be empty. Push something before log and check your array like this.
memoryList.push("test memory");
console.log(memoryList);

Related

Is this an Array of Object BUG? Ionic v6 React

As the image shows, it only renders one array of objects.
How to reproduce:
Create a Blank Template and paste this code on ExploreContainer.tsx:
import {
IonCard,
IonCardHeader,
IonCardSubtitle,
IonCardTitle,
IonCardContent,
} from '#ionic/react'
import { useEffect, useState } from 'react'
import './ExploreContainer.css'
interface ContainerProps {}
interface TestArrayObject {
key: string
id: string
name: string
age: number
}
const ExploreContainer: React.FC<ContainerProps> = () => {
const [testArray, setTestArray] = useState<TestArrayObject[]>([])
const arraySample: TestArrayObject[] = [
{
key: '1',
id: '12345',
name: 'Jack',
age: 40,
},
{
key: '2',
id: '67890',
name: 'Black',
age: 30,
},
]
useEffect(() => {
arraySample.map((arr: TestArrayObject) => {
setTestArray([...testArray, arr])
})
}, [])
const listArray = testArray.map((arr) => {
return (
<IonCard>
<IonCardHeader>
<IonCardSubtitle>{arr.id}</IonCardSubtitle>
<IonCardTitle>{arr.name}</IonCardTitle>
</IonCardHeader>
<IonCardContent>
Keep close to Nature's heart... {arr.age}
</IonCardContent>
</IonCard>
)
})
return <>{ listArray }</>
}
export default ExploreContainer
I'm trying to figure out the solution, but happens that i`m more than 24hours trying to figure out and nothing. could someone help?

NextJs nested dynamic routes based on API

I am stuck with Nextjs : I need to create nested dynamic routes based on my (local) data.
Here are the routes that I would like to create :
.../cars/ -> displays all the categories (sedan, suv, 4x4)
.../cars/category/ -> displays cars in the category
ex : .../cars/sedan -> displays cars in the sedan category
.../cars/category/id -> displays the details of the car from category which has id = 1
ex : .../cars/sedan/1 -> displays the details of the sedan car with id = 1
For routes 1 and 2 it's ok but I don't know how to do the last one. Can you help me please ?
data.js
export const cars = [
{
id: 1,
name: 'sedan',
models: [
{
id: 1,
name: 'model1',
image: '/sedan1.jpg',
},
{
id: 2,
name: 'model2',
image: '/sedan2.jpg',
},
{
id: 3,
name: 'model3',
image: '/sedan3.jpg',
},
],
},
{
id: 2,
name: 'suv',
models: [
{
id: 1,
name: 'model1',
image: '/suv1.jpg',
},
{
id: 2,
name: 'model2',
image: '/suv2.jpg',
},
{
id: 3,
name: 'model3',
image: '/suv3.jpg',
},
],
},
{
id: 3,
name: '4x4',
models: [
{
id: 1,
name: 'model1',
image: '/4x4_1.jpg',
},
{
id: 2,
name: 'model2',
image: '/4x4_2.jpg',
},
{
id: 3,
name: 'model3',
image: '/4x4_3.jpg',
},
],
},
];
/cars/index.js
import { cars } from '../../data';
import Link from 'next/link';
export default function Categories({ car }) {
return (
{car.map((c) => (
<Link key={c.id} href={`/cars/${c.name}`} passHref>
<div>{c.name}</div>
</Link>
))}
);
}
export const getStaticProps = async () => {
return {
props: {
car: cars,
},
};
};
/cars/[name].js
import React from 'react';
import { cars } from '../../data';
export default function CategoriesCars({ cars }) {
return (
<div>
{cars.models.map((m) => (
<p key={m.id}>{m.name}</p>
))}
</div>
);
}
export const getStaticPaths = async () => {
const paths = await cars.map((c) => ({
params: {
name: c.name,
},
}));
return { paths, fallback: false };
};
export const getStaticProps = async (context) => {
const { params } = context;
const response = await cars.filter((c) => c.name === params.name);
return {
props: {
cars: response[0],
},
};
};
The page folder must be:
pages/
cars/
[category]/
[id]/
index.jsx
index.jsx
then go /cars/sedan/2 you can access to category and id variables like this:
cars/[category]/[id]/index.jsx
import React from 'react';
import { useRouter } from 'next/router';
export default function Index() {
const router = useRouter();
// router.query.category -> sedan
// router.query.id -> 2
return <div>{JSON.stringify(router.query)}</div>;
}
// or
export const getServerSideProps = async (context) => {
const { params } = context;
console.log(params); // { category: 'sedan', id: '2' }
return {
props: {
cars: {},
},
};
};
// or if you wish use getStaticProps for SSG (with getStaticPaths)
export const getStaticPaths = async (context) => {
const paths = cars
.map((car) =>
car.models.map((model) => ({
params: {
id: model.id.toString(),
category: car.name,
},
}))
)
.flat(); // this is important
return { paths, fallback: false };
};
export const getStaticProps = async (context) => {
const { params } = context;
console.log(params);
return {
props: {
cars: {},
},
};
};
Example: StackBlitz

Why am I getting undefined after loading the page? But after refreshing the current page, I get normal data. How can I fix it? [duplicate]

This question already has answers here:
The useState set method is not reflecting a change immediately
(15 answers)
Closed 2 years ago.
I'm gettin undefined in hubConnection, and my program doesn't work, but after refreshing everything works correctly. I've tried to make hubConnection as simple property, but it didn't help me. One more thing that I've already tried is to create useRef hook and check if hubConnection if not undefined, if it not, then block the useEffect, but my messages after this action has stopped work.
Code of the program:
import React, { useCallback, useState, useEffect, useContext } from "react";
import { View, StyleSheet } from "react-native";
import { routes } from "../../../../Environment";
import { Icon } from 'react-native-elements'
import Font from "../../../data/fonts/Font";
import { GiftedChat, Bubble, Send, InputToolbar } from 'react-native-gifted-chat'
import { container } from 'tsyringe';
import ChatService from "../../../../api-service/chat-service/ChatService";
import { AuthContext } from "../../auth/AuthProvider";
import { HubConnection, HubConnectionBuilder } from "#microsoft/signalr";
const Chat = (props: any) => {
const chatService = container.resolve(ChatService);
const [messages, setMessages] = useState([]);
const [message, setMessage] = useState("");
const [hubConnection, setHubConnection] = useState<HubConnection>();
const { user } = useContext(AuthContext);
const getRandomInt = (max: number) => {
return Math.floor(Math.random() * Math.floor(max));
}
useEffect(() => {
setMessages([
{
_id: 1,
text: 'Hello dude',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
{
_id: 2,
text: 'Hello Tom',
createdAt: new Date(),
user: {
_id: user?.id.toString()!,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
{
_id: 3,
text: 'How are you?',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
},
])
const hubConnectionFunc = new HubConnectionBuilder()
.withUrl(routes.chatUrl)
.build();
hubConnectionFunc?.start().then(() => "Connection started!");
hubConnectionFunc.on("RecieveMessage", message => {
console.log(messages[0].text);
setMessages(previousMessages => GiftedChat.append(previousMessages, {
_id: getRandomInt(10000),
text: message,
createdAt: new Date(),
user: {
_id: user?.id.toString()!,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any',
},
}))
})
setHubConnection(hubConnectionFunc);
console.log(hubConnection);
}, [])
const onSend = useCallback((messages = []) => {
hubConnection?.invoke("SendMessage", messages[0].text)
.catch((err: any) => console.log(err));
setMessage("");
}, [])
const renderBubble = (props: any) => {
return (
<Bubble
{...props}
wrapperStyle={{
left: {
backgroundColor: "#F1F1F4",
},
right: {
backgroundColor: "#EB7A89"
}
}}
textStyle={{
left: {
color: "#000000"
},
right: {
color: "#FFFFFF"
}
}}
/>
);
}
const renderSend = (props: any) => {
return (
<Send {...props}>
<View style={styles.button}>
<Icon
name='paper-plane'
type='font-awesome'
color='white'
/>
</View>
</Send>
)
}
const renderInputToolbar = (props: any) => {
return (
<InputToolbar {...props} primaryStyle={{
borderWidth: 2,
justifyContent: "center",
alignItems: "center",
height: 44
}}
/>
)
}
return (
<View style={styles.chatWrapper}>
<GiftedChat
placeholder="Aa"
renderTime={() => <View></View>}
maxInputLength={500}
messages={messages}
onInputTextChanged={setMessage}
text={message}
onSend={onSend}
scrollToBottom
alwaysShowSend
user={{
_id: user?.id.toString()!,
name: user?.name!,
}}
renderBubble={renderBubble}
renderSend={renderSend}
renderInputToolbar={renderInputToolbar}
/>
</View >
)
}
NodeJS console after first loading
NodeJS console after refreshing the page
Some of your data not Loading 1st time but when you refresh your screen again it loads your data to fix this issue you can use async-await or && logic

quick replies press function (gifted chat) react native

I have worked on a chat app and I want to make a function when the user tab on one of these replies showed as user message in chat UI, and I want to know which quick reply he choose , anyone helps me?
this is code below:
import React, { Component } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
class App extends Component {
state ={
messages: [
{
_id: 1,
text: 'This is a quick reply. Do you love Gifted Chat? (radio) KEEP IT',
createdAt: new Date(),
user: {
_id: 2,
name: 'FAQ Bot',
avatar: 'https://i.imgur.com/7k12EPD.png'
},
quickReplies: {
type: 'radio', // or 'checkbox',
keepIt: true,
values: [
{
title: '😋 Yes',
value: 'yes',
},
{
title: '📷 Yes, let me show you with a picture!',
value: 'yes_picture',
},
{
title: '😞 Nope. What?',
value: 'no',
},
],
}
}
]
};
//................
onSend(messages = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, messages)
}));
}
onSend(quickReply = []) {
this.setState(previousState => ({
quickReply: GiftedChat.append(previousState.quickReply, quickReply)
}));
}
/*onSend(suggestions = []) {
this.setState(previousState => ({
messages: GiftedChat.append(previousState.suggestions, suggestions)
}));
}*/
render() {
return (
<View style={{ flex: 1, backgroundColor: '#fff' }}>
<GiftedChat
messages={this.state.messages}
quickReply={this.state.messages.quickReplies}
//messages={this.state.suggestions}
onSend={messages => this.onSend(messages)}
onQuickReply={quickReply => this.onQuickReply(quickReply)}
//onSend2={suggestions => this.onSend2(suggestions)}
user={{
_id: 1
}}
/>
</View>
);
}
}
export default App;
showed as user message in chat UI, and I want to know which quick reply he choose, anyone helps me?
You can get the chosen quick reply. And pass into chat.
onQuickReply(quickReply) {
if(quickReply[0].value == "yes") {
} else if (quickReply[0].value == "yes_picture") {
} else if (quickReply[0].value == "NO") {
}
let message = quickReply[0].value;
let msg = {
_id: this.state.messages.length + 1,
text: message,
createdAt: new Date(),
user: {
_id:1
}
}
this.setState(previousState => ({
messages: GiftedChat.append(previousState.messages, [msg])
}));
var sendBotResponsetxt = "Thanks";
this.sendBotResponse(sendBotResponsetxt);
}

Uncaught TypeError: this.state.imgData.map is not a function

Here id my Data file for image
imageData = [
{
id: 1,
imgName: "Apple",
imgFile: "apple.jpg",
imgQuestion: "Which fruit is this",
imgAnswer: "This is an Apple"
},
{
id: 2,
imgName: "Orange",
imgFile: "orange.jpg",
imgQuestion: "What is the color of Orange",
imgAnswer: "The color of orange os orange"
},
{
id: 3,
imgName: "Mango",
imgFile: "mango.jpg",
imgQuestion: "Do you like Mangoes",
imgAnswer: "Yes I like Mangoes"
}
]
I don't know why my code is showing error message in browser console:
Uncaught TypeError: this.state.imgData.map is not a function
import React, { Component } from 'react';
import Jokes from './../components/Jokes';
import Data from './../data';
export default class Index extends Component {
constructor() {
super()
this.state = {
imgData: Data
}
}
render() {
const imgDataItem = this.state.imgData.map(item => {
<Jokes data={{key: this.item.id}}
data={{
img: this.item.imgName,
imgFileName: this.item.imgFile,
question: this.item.imgQuestion,
answer: this.item.imgAnswer
}}
/>
})
return (
{imgDataItem}
)
}
}
I am new to react and please get me the solution where I am getting wrong
Try destructuring with assignment by default value for imgData
render() {
const {imgData = []} = this.state;
const imgDataItem = imgData.map(item => {
<Jokes data={{key: this.item.id}}
data={{
img: this.item.imgName,
imgFileName: this.item.imgFile,
question: this.item.imgQuestion,
answer: this.item.imgAnswer
}}
/>
})
return (
{imgDataItem}
)
}

Resources