React Native Country PickerView error when selecting a country - javascript

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?

Related

Element does not exist in React's componentDidMount

I have following react component:
var ForumActivityTimeLine = React.createClass({
componentDidMount: function () {
this.showActivityLineChart()
},
showActivityLineChart() {
const lineChartSpec = getForumActivityLineChart(this.props.data.frequency)
const opt = {
renderer: "canvas",
actions: false
};
vegaEmbed('#ForumActivityLineChart', lineChartSpec, opt)
},
render() {
return (
<span>
<h5 style={{ textAlign: "center", fontWeight: "bold", display: "block", paddingTop: '2em' }}> Forum Activity Timeline</h5>
<div className="d-flex justify-content-around" style={{ paddingTop: "0.5em" }}>
<div id='#ForumActivityLineChart'></div>
</div>
</span>
)
}
})
vegaEmbed line is trying to render a line chart in the div with id ForumActivityLineChart, but it gives me following error:
embed.ts:296 Uncaught (in promise) Error: #ForumActivityLineChart does not exist
at Kn (embed.ts:296:11)
at Jn (embed.ts:259:16)
Here is the error desscription in console:
In chrome dev tools console, you can see that the corresponding div element does exist (ignore setTimeout call in snapshot, I thought if I can dirty set some timeout to let the component render first):
Here is another screenshot, where debugger stops before throwing exception:
PS: I am working on legacy react app, thats why I have var and componentDidMount.
You should not include # in the id-attribute.
Replace
<div id='#ForumActivityLineChart'></div>
with
<div id='ForumActivityLineChart'></div>

Error while connecting sanity content lake to frontend

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}
/>

Unable to render {message} object in the Chrome Console

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.

React ComboBox (npm component) returning [object Object]

I've currently set a task for myself of creating a language selection box, using https://react-combobox.netlify.app/demo as a base and working off of that as I learn React. The code so far I have is returning [object Object] as a result when I select an entry in the combobox.
Code:
import React, { useState } from "react";
import ComboBox from "react-responsive-combo-box";
export default function ComboBoxLang(props) {
const [selectedOption, setSelectedOption] = useState("");
const [highlightedOption, setHighlightedOption] = useState("");
const options = props.dataSet.map ( (inputValue) => {
// const columnWidth = props.columnsWidth.language_name + "px";
const columnWidth = props.columnsWidth;
let keys = Object.keys(columnWidth);
console.log ('keys are' + keys)
const renderedColumns = keys.map( columnName =>{
return(
<div style={{display:"inline-block", width:columnWidth[columnName]}}>{inputValue[columnName]} </div>
);
})
return (
<div key={inputValue.id}>
{renderedColumns}
</div>
)
})
return (
<div>
<h1>React Combo Box</h1>
<p>
The selected option -{" "}
<span style={{ fontWeight: "bold" }}>
{" "}
{selectedOption.length > 0 ? selectedOption : "None"}
</span>
</p>
<p>
The highlighted option -{" "}
<span style={{ fontWeight: "bold" }}>
{" "}
{highlightedOption.length > 0 ? highlightedOption : "None"}
</span>
</p>
<ComboBox
options={options}
placeholder="choose country"
defaultIndex={4}
optionsListMaxHeight={300}
style={{
width: "500px",
margin: "0 auto",
marginTop: "50px"
}}
focusColor="#20C374"
renderOptions={(option) => (
<div className="comboBoxOption">{option}</div>
)}
onSelect={(option) => setSelectedOption(option)}
onChange={(event) => console.log(event.target.value)}
enableAutocomplete
onOptionsChange={(option) => setHighlightedOption(option)}
/>
</div>
);
}
index.js code:
import React from 'react';
import ReactDOM from 'react-dom';
import ComboBoxLang from './combobox_test.js';
const languages = [
{
"id": 1,
"language_name": "Afrikaans",
"language_native_name": "Afrikaanse taal",
"language_full_name": "Afrikaanse taal (Afrikaans)",
"language_code": "af",
"translation_engine_id": 2,
"translation_engine_name": "Google"
},
{
"id": 2,
"language_name": "Albanian",
"language_native_name": "Gjuha shqipe",
"language_full_name": "Gjuha shqipe (Albanian)",
"language_code": "sq",
"translation_engine_id": 2,
"translation_engine_name": "Google"
}
];
class App extends React.Component {
render () {
return (
<div>
<ComboBoxLang dataSet={languages} columnsWidth={{language_name:200,language_native_name:300}}/>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('drop-down-menu')
);
The goal is to effectively have the language, and the native language (or language code at a later date) to display within the combo-box once selected. I've left the 2 "Displayed" and "Selected" boxes so that, once it works, I can understand a bit how it works, and allow other things to interact or reference those items. For now, I am stuck trying to figure out why it spit's out [object Object] and where it is actually in need of correcting.

react-native-google-places-autocomplete give it a value rather than just default (initial) value

I have a working <TextInput>:
<TextInput
placeholder="Location"
value={props.locationInput.toString()}
onChangeText={location => props.updateLocationInput(location)}
/>
The props.locationInput is initially '' but as soon as the app starts, a couple of async functions fire and get the users current location which populate the props.locationInput (in a redux store). This means the <TextInput> above displays the users current location when it arrives. I want to basically just do exactly as above, but with a react-native-google-places-autocomplete
The react-native-google-places-autocomplete does initialise with the props.locationInput value. It has a getDefaultValue property eg getDefaultValue={() => props.locationInput.toString()}, however it doesn't change when the props.locationInput changes, so it never displays the users current location because that isn't set when it initialises. How do I get the react-native-google-places-autocomplete to update when props.locationInput changes?
Possibly thinking I may need to not render it until the users current location comes in but that is really messy.
EDIT: Also looking into not using the plugin and instead doing calls to google places API.
Late to the game, but there is function named setAddressText.
Example:
setLocation(text) {
this.placesRef && this.placesRef.setAddressText(text)
}
...
<GooglePlacesAutocomplete
ref={ref => {this.placesRef = ref}}
...
/>
On the GooglePlaceAutocomplete component you have to use the onPress event to get the value. Here is an example:
<GooglePlacesAutocomplete
placeholder='Event Location'
minLength={2} // minimum length of text to search
autoFocus={false}
// Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
listViewDisplayed='auto' // true/false/undefined
fetchDetails={true}
renderDescription={row => row.description} // custom description render
onPress={(data, details = null) => {
// 'details' is provided when fetchDetails = true
this.setState(
{
address: data.description, // selected address
coordinates: `${details.geometry.location.lat},${details.geometry.location.lng}` // selected coordinates
}
);
}}
textInputProps={{
onChangeText: (text) => { console.warn(text) }
}}
getDefaultValue={() => ''}
query={{
// available options: https://developers.google.com/places/web-service/autocomplete
key: 'XXXXXXXXXXXXXXZXZXXXXXXX',
language: 'en', // language of the results
types: 'geocode' // default: 'geocode'
}}
styles={{
textInputContainer: {
backgroundColor: 'rgba(0,0,0,0)',
borderTopWidth: 0,
borderBottomWidth:0,
},
description: {
fontWeight: 'bold',
},
textInput: {
marginLeft: 22,
marginRight: 0,
height: 38,
color: '#5d5d5d',
fontSize: 16,
},
predefinedPlacesDescription: {
color: '#1faadb'
}
}}
value={props.location}
onChangeText={props.onLocationChange}
renderLeftButton={() => <Text style={{ marginTop: 12, marginLeft:16, fontSize: 18 }}> Location </Text>}
nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
GoogleReverseGeocodingQuery={{
// available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
}}
GooglePlacesSearchQuery={{
// available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
rankby: 'distance',
types: 'food'
}}
filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
/>
using react functional hooks
<GooglePlacesAutocomplete
...
ref={ref => {
ref?.setAddressText('123 myDefault Street, mycity')
}}
/>

Categories