I am using {message} from the props in a component in the ReactJS.
The code is given below
import React from "react";
const MyMessage = ({ message }) => {
if (message?.attachments?.length > 0) {
return (
<img
src={message.attachments[0].file}
alt="message_attachment"
className="message-image"
style={{ float: "right" }}
/>
);
}
const msg = JSON.stringify(message);
console.log("fmsg = "+ msg.sender)
console.log("mes = "+JSON.stringify(message))
console.log("now = "+msg.first_name)
return (
<div
className="message"
style={{
float: "right",
marginRight: "18px",
color: "white",
backgroundColor: "#3B2A50",
}}
>
{message?.text}
</div>
);
};
export default MyMessage;
What I tried?
I used the following console stmts:
console.log(message); -> [Object Object]
console.log(JSON.stringify(message));
{
"id":455890,
"sender":{
"username":"GMmohit",
"first_name":"Mohit",
"last_name":"Maroliya",
"avatar":"https://api-chat-engine-io.s3.amazonaws.com/avatars/potrait_rKDI2hb.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAZA5RH3EC2MM47GFP%2F20220213%2Fca-central-1%2Fs3%2Faws4_request&X-Amz-Date=20220213T141431Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=1d5e0ec2418701210532824ba90af5f6366d17b7fa1f9dfadb6783cd8efdbfd6",
"custom_json":"{}",
"is_online":true
},
"created":"2022-02-12 12:23:04.745937+00:00",
"attachments":[],
"sender_username":"undefined",
"text":"----",
"custom_json":"{}"
}
const msg = JSON.stringify(message)
console.log("now = "+msg.first_name) -> but it gives undefined
How can I access the values in {message} like username,first_name etc? However, I am able to access message?.text .
It looks like your username and first name are coming off the sender object in your message. You'll need to consider the sender like:
message.sender.username
to access the username that is in the sender object in the message.
If you are stringifying your json, you will not be able to take data from it, because it will serve as a whole string not as an object.
Related
I'm getting an error while fetching blogs from sanity to my template, I'm creating a next.js website
Error: Error: Unknown block type "undefined", please specify a
serializer for it in the serializers.types prop
<PortableText
// Pass in block content straight from Sanity.io
content={blogs[0].content}
projectId="oeqragbg"
dataset="production"
// Optionally override marks, decorators, blocks, etc. in a flat
// structure without doing any gymnastics
serializers = {{
h1: (props) => <h1 style={{ color: "red" }} {...props} />,
li: ({ children }) => <li className="special-list-item">{children}</li>,
}}
/>
export async function getServerSideProps(context) {
const client = createClient({
projectId: 'oeqragbg',
dataset: 'production',
useCdn: false
});
const query = '*[_type == "blog"]';
const blogs = await client.fetch(query);
return {
props: {
blogs
}
}
}
Are you using the #portabletext/react package?
This is how you would use it:
import {PortableText} from '#portabletext/react'
const myPortableTextComponents = {
block: {
h1: ({children}) => <h1 style={{ color: "red" }}">{children}</h1>
},
listItem: {
bullet: ({children}) => <li className="special-list-item">{children}</li>,
},
}
<PortableText
value={blogs[0].content}
components={myPortableTextComponents}
/>
I have a country picker view component from the 'react-native-country-picker-modal' package. When I click on it it opens a list of all the countries with their flag and code, but when i click on any one of the countries i get this error "Type Error: undefined is not an object (evaluating 'countries[countryCode].name')" and "Type Error: undefined is not an object (evaluating str.indexOf)"
here is my code:
import CountryPicker from 'react-native-country-picker-modal'
const [callingCode, setCallingCode] = useState('+1')
const [countryCode, setCountryCode] = useState('US')
<CountryPicker
style={{ height: 40, width: 60 }}
countryCode={countryCode}
translation={'ita'}
withCallingCodeButton
withAlphaFilter
withFilter
visible={false}
onClose={() => {
// this.setState({showCountry : false})
}}
onSelect={(country) => {
setCallingCode(country.cca2)
setCountryCode(country.callingCode)
}}
/>
What am i doing wrong?
I am getting an error which I am not able to understand or shake. What I am trying to do is that on click of a button I am trying to change the value in the text field in the form I created Howerver I am getting this error:
Cannot create property label on string for one of the instances.
Here is the function where I am trying to change the values:
getReport(ReportList) {
this.state.SPCCODE.label = 'NA';
this.state.destinationcode.label = 'NA'
}
I am declaring SPCCODE in the state as
SPCCODE: '',
destinationcode: '',
I am declaring SPCCODE as conditional render in render like so:
let DDL;
const DDLValue = servicecode.label;
if (DDLValue == 'Direct') {
DDL = <> </>;
} else if (DDLValue == 'STYD') {
DDL = <> </>;
} else {
DDL = (
<Col lg="6" style={{ marginTop: '0rem' }}>
<Label for="spcc">SPC</Label>
<Select
className="select"
id="spc"
// value={servicecode}
placeholder="Search spcCode..."
value={hide ? null : SPCCODE}
onChange={this.handleChangeSPC}
options={this.state.spcCode}
isDisabled={this.state.disable}
styles={{
control: (provided, state) => ({
...provided,
boxShadow: 'none',
// borderBottom: "1px dotted pink",
borderBottom: this.state.isEmpty4 ? '1px solid red' : '1px solid black',
}),
}}
/>
</Col>
);
}
I am handling the SPC CODE change in this function:
handleChangeSPC = SPCCODE => {
this.setState({ hide: false });
this.setState({ SPCCODE });
var spc_label = SPCCODE.label;
this.setState({ spc_label });
};
I am calling the g getReport() function from a child component table like this
passVariable() {
this.props.getReport(this.state.ReportList);
}
I am calling this onClick
On researching I am getting that may it is showing the error because the variable is immutable but have not anywhere declared it in const. Please help do not know why exactly this error is showing?
The problem is that you declare SPCCODE as string in the state then trying to access to non-existent property label inside it. It is not possible and throw type error.
To solve it, you must declare it like literal object such as:
SPCCODE: {label:''}
If I make this call but the pokemon I've entered doesn't have a second type I get this error message:
Is it possible to make an if statement within the useState hook that I've named setPokemon?
If so, how can I do that or how can I get through this?
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 [pokemon, setPokemon] = useState({});
const [pokemonDescription, fetchDescription] = useState({});
const [evolution, pokemonEvolution] = useState({});
const searchPokemon = () => {
api.get(`pokemon/charmander`).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,
});
});
});
});
};
return (
<div>
<div className="main">
<h1 style={{ textTransform: "capitalize" }}>{pokemon.name}</h1>
<h1>No. {pokemon.id}</h1>
<img src={pokemon.img} alt="" />
</div>
<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 className="desc">
<div className="desc-info">
<h3 style={{ textTransform: "capitalize" }}>
{pokemonDescription.entry}
</h3>
</div>
</div>
<h1 style={{ textTransform: "capitalize" }}>
Evolution: {evolution.evolution}
</h1>
<button onClick={searchPokemon}>Click me</button>
</div>
);
}
export default PK;
If we first look at your error, the index 1 of your types array from your api response data is not defined. Therefore, when you try to access, it throws.
When you are not certain of the response of your api, you can use a combination of optional chaining and setting default values for that property.
This way, your code won’t break.
In your example, I believe you could do something like:
const response = {
data: {
types: []
}
};
console.log(response.data.types[1]?.type.name ?? "pick a value or leave an empty string");
// type2: response.data.types[1]?.type.name ?? ""
Notice the question mark I’ve added right after the index 1 of your expected types array. This symbol allows for optional chaining.
Then we use Nullish coalescing operator (??).
So I'm trying to reproduce a simple example code of react-qr-scanner, but in the code below as I try to embed result in the p tag I get an error, saying objects cannot be embedded inside that. What am I doing wrong?
import React, { Component } from 'react';
import QrReader from 'react-qr-scanner';
class Scan extends Component {
constructor(props) {
super(props);
this.state = {
result : 'Hold QR Code steady and clear to scan',
}
this.previewStyle = {
height : 700,
width : 1000,
display : 'flex',
justifyContent : "center",
}
this.camStyle = {
display : 'flex',
justifyContent : 'center',
marginTop : '-50px',
}
this.textStyle= {
fontSize : '30px',
"text-align" : 'center',
marginTop : '-50px',
}
this.handleScan = this.handleScan.bind(this);
}
handleScan(data) {
this.setState({
result : data,
});
}
handleError(err) {
console.log(err);
}
render() {
return (
<>
<div className="stream-container" >
<QrReader
delay={100}
onError={this.handleError}
onScan={this.handleScan}
/>
</div>
<p style={this.resultStyle}>
{this.state.result} //here error occurs saying I cannot embed it inside here
</p>
</>
);
}
}
export default Scan;
The docs of react-qr-scanner has this exact example, so why isn't it working on mine? Please help.
In the function of handleScan, data is an object, 'Objects are not valid as a React child'.
Try to make your fuctions with arrow -
handleScan = (data) => {
this.setState({
result: data,
});
}
handleError = (err) => {
console.log(err);
}