react native react-native-geocoding address will not render - json

i am creating an app to display user add using react native
after getting user permission and latitude,longitude using expo i used react-native-geocoding to turn cords to address but address would not display
expo permission code
import React from 'react';
import { Alert,Platform,StyleSheet, Text, View } from 'react-native';
import { Constants, Location, Permissions } from 'expo';
import AppStackNav from '../party/src/nav/appStackNav';
import Geocoder from 'react-native-geocoding';
Geocoder.init('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
export default class App extends React.Component {
state = {
location: null,
errorMessage: null,
addressComponent: null,
};
componentWillMount() {
this._getLocationAsync();
}
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
this.setState({
errorMessage: 'Permission to access location was denied',
});
}
let location = await Location.getCurrentPositionAsync({
enableHighAccuracy: true,
});
this.setState({ location });
let lat = this.state.location.coords.latitude;
let long = this.state.location.coords.longitude;
Geocoder.from(lat,long).then(json =>
{
var addressComponent = json.results[0].formatted_address;
this.setState({addressComponent})
// Alert.alert(this.state.addressComponent)
})
}
then attempt to display the address while passing as a prop
import React, {Component} from 'react';
import {View,Text,StyleSheet,FlatList} from 'react-native'
import styles from '../style/styles';
class SetConn extends Component {
render(){
return(
<View>
<Text style={styles.addyComp}>{this.props.addressComponent}</Text>
</View>
);
}
}
export default SetConn;

the react-native-geocoder api works from human readable address -> latitude longitude.
Use google reverse geocoding instead.

Related

useFirestoreConnect returns empty object in react redux firebase

I am trying to create a todo app using react redux firebase. I have been able to connect the react redux firebase library to firebase as my create task actions produces changes in the firestore. But the redux store does not seem to be connected to firestore which is why I receive an empty object in console.log when i use fireStoreConnect in the useSelector hook.
store.js
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
// Redux
import { applyMiddleware, legacy_createStore as createStore } from 'redux';
import thunk from 'redux-thunk';
import { getFirebase } from 'react-redux-firebase';
import { getFirestore } from 'redux-firestore';
import { createFirestoreInstance } from 'redux-firestore';
// Reducers
import rootReducer from './reducers/rootReducer';
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: 'AIzaSyDOka0NyhrtvdX3hQihX0yVgHQ3m9f6Alg',
authDomain: 'todo-list-720.firebaseapp.com',
projectId: 'todo-list-720',
storageBucket: 'todo-list-720.appspot.com',
messagingSenderId: '770009943120',
appId: '1:770009943120:web:02fbc5adb060ee2cbc9555',
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize Firestore
firebase.firestore();
const rrfConfig = {
userProfile: 'users',
useFirestoreForProfile: true,
};
const store = createStore(
rootReducer,
applyMiddleware(thunk.withExtraArgument({ getFirebase, getFirestore }))
);
const rrfProps = {
firebase,
config: rrfConfig,
dispatch: store.dispatch,
createFirestoreInstance,
};
export { store, rrfProps };
Home.js
import { useSelector } from 'react-redux';
import { useFirestoreConnect } from 'react-redux-firebase';
// Components
import Navigation from '../components/Navigation';
import TaskList from '../components/TaskList';
import AddTask from '../components/AddTask';
const Home = () => {
useFirestoreConnect(['tasks']);
const tasks = useSelector((state) => {
console.log(state.firestore);
return state.firestore.data.tasks;
});
return (
<>
<Navigation />
<AddTask />
<TaskList tasks={tasks} />
</>
);
};
export default Home;
rootReducer.js
import { firebaseReducer } from 'react-redux-firebase';
import { firestoreReducer } from 'redux-firestore';
const rootReducer = combineReducers({
firebase: firebaseReducer,
firestore: firestoreReducer,
/* auth: authReducer, */
tasks: tasksReducer,
});
image of firestore collection
CodeSandbox Link

Shopify - How do I route between pages

I am new to Shopify App development and I try to implement routing inside my embedded Shopify App.
I have setup the ClientRouter and also integrated it inside the app.js (see below). When I set Navigation Links through the partners Account, the navigation menu appears and the links and the redirecting work as well.
As soon as I try to navigate the user to a page on a Button click, I get the error:
Expected a valid shop query parameter
I am trying to navigate the user by just giving the path for the page:
<Button url="/users">Users</Button>
My other files are listed below:
index.js
import { Page, Heading, Button } from "#shopify/polaris";
const Index = () => (
<Page>
<Heading>Index PAGE</Heading>
<Button url="/users"> Users </Button>
</Page>
);
export default Index;
app.js
import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";
import App from "next/app";
import { AppProvider } from "#shopify/polaris";
import { Provider, useAppBridge } from "#shopify/app-bridge-react";
import { authenticatedFetch } from "#shopify/app-bridge-utils";
import { Redirect } from "#shopify/app-bridge/actions";
import "#shopify/polaris/dist/styles.css";
import translations from "#shopify/polaris/locales/en.json";
import ClientRouter from "../components/ClientRouter";
function userLoggedInFetch(app) {
const fetchFunction = authenticatedFetch(app);
return async (uri, options) => {
const response = await fetchFunction(uri, options);
if (
response.headers.get("X-Shopify-API-Request-Failure-Reauthorize") === "1"
) {
const authUrlHeader = response.headers.get(
"X-Shopify-API-Request-Failure-Reauthorize-Url"
);
const redirect = Redirect.create(app);
redirect.dispatch(Redirect.Action.APP, authUrlHeader || `/auth`);
return null;
}
return response;
};
}
function MyProvider(props) {
const app = useAppBridge();
const client = new ApolloClient({
fetch: userLoggedInFetch(app),
fetchOptions: {
credentials: "include",
},
});
const Component = props.Component;
return (
<ApolloProvider client={client}>
<Component {...props} />
</ApolloProvider>
);
}
class MyApp extends App {
render() {
const { Component, pageProps, host } = this.props;
return (
<AppProvider i18n={translations}>
<Provider
config={{
apiKey: API_KEY,
host: host,
forceRedirect: true,
}}
>
<ClientRouter />
<MyProvider Component={Component} {...pageProps} />
</Provider>
</AppProvider>
);
}
}
MyApp.getInitialProps = async ({ ctx }) => {
return {
host: ctx.query.host,
API_KEY: process.env.SHOPIFY_API_KEY,
};
};
export default MyApp;
ClientRouter.js
import { withRouter } from "next/router";
import { ClientRouter as AppBridgeClientRouter } from "#shopify/app-bridge-react";
function ClientRouter(props) {
const { router } = props;
return <AppBridgeClientRouter history={router} />;
}
export default withRouter(ClientRouter);
I am really looking forward to someone who can help me out! Thanks in advance!

Cannot read property 'map' of undefined in React + Phoenix framework

I'm new to React. I have provided Postgresql API and I want to add those data in Material UI Table.
I've made some mistakes and I'm unable to figure to out.
I'm using API calls for the first time using Axios. So please guide me to solve this issue.
I'm using React.js for frontend work, Phoenix framework for backend, and PostgreSQL database.
The below component is used to handle API request using Axios
import axios from "axios"
import MedicineCard from './MedicineCard'
class Medicines extends React.Component {
constructor() {
super();
this.state = { medicines: [] };
}
componentWillMount() {
axios.get('http://localhost:4000/medicines')
.then(response => {
this.setState({ medicines: response.data.medicines });
})
.catch(error => {
console.log(error);
});
}
render() {
const posts = this.state.medicines.map((medicine, index) =>
<MedicineCard
key = { index }
medid = {medicine.medid}
medname = {medicine.medname}
/>
)
return (
<div>
{posts}
</div>
)
}
}
export default Medicines
Below Component is used for Material UI Table
import React from 'react'
import MaterialTable from 'material-table'
class MedicineCard extends React.Component{
render(){
const data=[
{medid:this.props.medid,medname:this.props.medname}
]
const column=[
{
title:'Medicine_ID',field:'medid'
},
{
title:'Medicine_Name',field:'medname'
}
]
return (
<div>
<MaterialTable title="Material Table"
data={data}
column ={column}
/>
</div>
);
}
}
export default MedicineCard
This component is used to display UI
import React from 'react'
import Medicines from './Medicines'
const Test = () => (
<div>
<Medicines />
</div>
)
export default Test
Please help me and guide me out to solve this issue

Unit Testing to see if JSON file is null

I am currently trying to unit test a container that pulls in a static JSON file of phone numbers and passes it to the component to display, however I am not sure how I should go about testing it. The code for the container is as follows:
import React from 'react';
import data from *JSON file location*
import CountryInfo from *component for the country information* ;
class CountryInfoContainer extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
numbersJson: null
};
}
async componentWillMount() {
const numbersJson = data;
this.setState({ numbersJson });
}
render() {
return (
<CountryInfo json={this.state.numbersJson} showText={this.props.showText} />
);
}
}
export default CountryInfoContainer;
I currently have my unit test to look like this
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { mount, configure } from 'enzyme';
import { MemoryRouter } from 'react-router-dom';
import CountryInfoContainer from './CountryInfoContainer';
configure({ adapter: new Adapter() });
describe('Successful flows', () => {
test('checks if json has null entries', () => {
const wrapper = mount(<MemoryRouter><CountryInfoContainer /></MemoryRouter >);
const data = wrapper.find(numbersJson);
// eslint-disable-next-line no-console
console.log(data.debug);
});
});
Obviously, it doesn't work now because I am not sure how to use the variable numbersJson in the container in the test file or how to check if it is null.
The variable numbersJson is not defined in the scope of your test. If I understand correctly, you are testing that when you first mount the component, that it's state contains a null value for the numbersJson key.
First of all, you need to mount your component directly without MemoryRouter:
const wrapper = mount(<CountryInfoContainer />);
Then you can write an expect() for the state:
expect(wrapper.state().numbersJson).toBeNull();

Using Jest to test a Link from react-router v4

I'm using jest to test a component with a <Link> from react-router v4.
I get a warning that <Link /> requires the context from a react-router <Router /> component.
How can I mock or provide a router context in my test? (Basically how do I resolve this warning?)
Link.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import { Link } from 'react-router-dom';
test('Link matches snapshot', () => {
const component = renderer.create(
<Link to="#" />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
The warning when the test is run:
Warning: Failed context type: The context `router` is marked
as required in `Link`, but its value is `undefined`.
You can wrap your component in the test with the StaticRouter to get the router context into your component:
import React from 'react';
import renderer from 'react-test-renderer';
import { Link } from 'react-router-dom';
import { StaticRouter } from 'react-router'
test('Link matches snapshot', () => {
const component = renderer.create(
<StaticRouter location="someLocation" context={context}>
<Link to="#" />
</StaticRouter>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
Have a look at the react router docs about testing
I had the same issue and using StaticRouter would still require the context which needed more configuration to have it available in my test, so I ended up using the MemoryRouter which worked very well and without any issues.
import React from 'react';
import renderer from 'react-test-renderer';
import { MemoryRouter } from 'react-router-dom';
// SampleComponent imports Link internally
import SampleComponent from '../SampleComponent';
describe('SampleComponent', () => {
test('should render', () => {
const component = renderer
.create(
<MemoryRouter>
<SampleComponent />
</MemoryRouter>
)
.toJSON();
expect(component).toMatchSnapshot();
});
});
The answer of #Mahdi worked for me! In 2023 if you want to test a component that includes <Link> or <NavLink>, we just need to wrap it with the <MemoryRouter> in the test file:
// App.test.js
import { render, screen } from "#testing-library/react";
import MyComponent from "./components/MyComponent";
import { MemoryRouter } from "react-router-dom"; // <-- Import MemoryRouter
test("My test description", () => {
render(
<MemoryRouter> // <-- Wrap!
<MyComponent />
</MemoryRouter>
);
});
my test like this:
import * as React from 'react'
import DataBaseAccout from '../database-account/database-account.component'
import { mount } from 'enzyme'
import { expect } from 'chai'
import { createStore } from 'redux'
import reducers from '../../../reducer/reducer'
import { MemoryRouter } from 'react-router'
let store = createStore(reducers)
describe('mount database-account', () => {
let wrapper
beforeEach(() => {
wrapper = mount(
< MemoryRouter >
<DataBaseAccout store={store} />
</MemoryRouter >
)
})
afterEach(() => {
wrapper.unmount()
wrapper = null
})
})
but I don't konw why MemoryRouter can solve this。
Above solutions have a common default defact:
Can't access your component's instance! Because the MemoryRouter or StaticRouter component wrapped your component.
So the best to solve this problem is mock a router context, code as follows:
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
describe('YourComponent', () => {
test('test component with react router', () => {
// mock react-router context to avoid violation error
const context = {
childContextTypes: {
router: () => void 0,
},
context: {
router: {
history: createMemoryHistory(),
route: {
location: {
hash: '',
pathname: '',
search: '',
state: '',
},
match: { params: {}, isExact: false, path: '', url: '' },
}
}
}
};
// mount component with router context and get component's instance
const wrapper = mount(<YourComponent/>, context);
// access your component as you wish
console.log(wrapper.props(), wrapper.state())
});
beforeAll(() => {
configure({ adapter: new Adapter() });
});
});