not a system font error, might be related to async? - javascript

So I got the "Roboto-Black" is not a system font, try putting through Expo.Font.loadAsync() error. but I've read in other posts that some people are having similar problems and the solution is by using await/promise.
However, Im not sure how to do that with my code since I'm just following a tutorial to do this and this is my first attempt using create-react-native-app with minimum JS knowledge :(
Please help me inspect this code snippet and let me know what I did wrong:
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { Font, AppLoading } from 'expo';
import Router from 'loginDemo/config/routes.js'
import store from 'loginDemo/redux/store.js';
function cacheFonts(fonts) {
return fonts.map(function(font) {return Font.loadAsync(font)});
}
export default class App extends Component {
constructor() {
super();
this.state = {
isReady: false,
}
}
async _loadAssetsAsync() {
const fontAssets = cacheFonts([
{RobotoBlack: require('loginDemo/assets/fonts/Roboto-Black.ttf')},
{RobotoBold: require('loginDemo/assets/fonts/Roboto-Bold.ttf')},
{RobotoMedium: require('loginDemo/assets/fonts/Roboto-Medium.ttf')},
{RobotoRegular: require('loginDemo/assets/fonts/Roboto-Regular.ttf')},
{RobotoLight: require('loginDemo/assets/fonts/Roboto-Light.ttf')}
]);
await Promise.all([...fontAssets]);
}
render() {
if (!this.state.isReady) {
return (
<AppLoading
startAsync={this._loadAssetsAsync}
onFinish={() => this.setState({isReady: true})}
onError={console.warn}
/>
);
}
return (
<Provider store={store}>
<Router/>
</Provider>
);
}
}

Related

TypeError: Cannot read property 'find' of undefined in React-redux while running a test

I know there has been a lot of "cannot read property ".find" fo undefined" questions, but I have been looking at them and have not found an answer that I am looking for.
I am running a test of my components.. and this one does not pass.. I was able to make the other tests pass.. but the ".find" returns an undefined error.. been looking at it the whole morning, but cannot find the solution.. can anybody help me?
Here is the commentList.test.js file:
import React from 'react';
import { mount } from 'enzyme';
import { CommentList } from 'components/commentList';
import Root from 'Root';
let wrapped;
beforeEach(() => {
const initialState = {
comments: ['Comment 1', 'Comment 2']
};
wrapped = mount(
<Root initialState={initialState}>
<CommentList />
</Root>
);
});
it('creates one LI per comment', () => {
expect(wrapped.find('li').length).toEqual(2);
});
Here is the commentList.js file
import { connect } from 'react-redux';
import React, { Component } from 'react';
class CommentList extends Component {
renderComments() {
return this.props.comments.map(comment => {
return <li key={comment}>{comment}</li>
})
}
render() {
return (
<div>
<ul>
{this.renderComments()}
</ul>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
comments: state.comments
};
}
export default connect(mapStateToProps)(CommentList);
and finally the Root.js file:
import React from 'react';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from 'reducers';
export default ({ children, initialState = {} }) => {
return (
<Provider store={createStore(reducers, initialState)}>
{children}
</Provider>
)
}
Here is what can bee seen in my terminal
enter image description here
This may have come a little bit late.. I was not able to give my answer at that time because I have not the required reputation to give an answer.. lol.. but for those who have been following this question and wondering where i did the fix.. here it is:
replace this line of code
import { CommentList } from 'components/commentList';
with this:
import CommentList from 'components/commentList';
Hope this will be helpful for someone out there.
try looking for hostnodes:
it('creates one LI per comment', () => {
expect(wrapped.hostNodes().find('li').length).toEqual(2);
});
https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/hostNodes.md

What is wrong with my render method here?

I'm writing an example app over here to get my head around React but one of my simpler components is throwing an error that I can't seem to track.
Error: Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
undefined. You likely forgot to export your component from the file
it's defined in. Check the render method of ContactListItem.
Here's the code for the ContactListItem component.
import React, { Component } from 'react';
import { ListGroupItem } from 'react-bootstrap';
import { Link } from 'react-router';
class ContactListItem extends Component {
render() {
const { contact } = this.props;
return (
<ListGroupItem>
<Link to={'/contact/${contact.id'}>
<h4>{contact.name}</h4>
</Link>
</ListGroupItem>
);
}
}
export default ContactListItem;
It's a pretty simple class. Nothing sticks out to me as problematic. For completion's sake, here's the parent component.
import React, { Component } from 'react';
import { ListGroup } from 'react-bootstrap';
import ContactActions from '../actions/ContactActions';
import ContactStore from '../stores/ContactStore';
import ContactListItem from './ContactListItem';
function getContactListItem(contact) {
return (
<ContactListItem key={contact.id} contact={contact} />
);
}
class ContactsComponent extends Component {
constructor() {
super();
this.state = {
contacts: []
}
this.onChange = this.onChange.bind(this);
}
componentWillMount() {
ContactStore.addChangeListener(this.onChange);
}
componentDidMount() {
ContactActions.receiveContacts()
}
componentWillUnmount() {
ContactStore.removeChangeListener(this.onChange);
}
onChange() {
this.setState({
contacts: ContactStore.getContacts()
});
}
render() {
let contactListItems;
if ( this.state.contacts ) {
contactListItems = this.state.contacts.map(contact => getContactListItem(contact));
}
return (
<div>
<ListGroup>
{contactListItems}
</ListGroup>
</div>
);
}
}
export default ContactsComponent;
You get the error in ContactListItem#render() because Link is undefined. As of React Router v4, <Link /> is no longer a part of the react-router, but a part of the react-router-dom package. Changing this should fix your problem:
import { Link } from 'react-router-dom';
As per documentation,
use
import { Link } from 'react-router-dom';`
unlike react-router which used to work earlier.
But react-router-dom comes with:
HashRouter
BrowserRouter
MemoryRouter
Prompt
NavLink
StaticRouter, etc.
You might benefit from tree-shaking a lot, on using
import Link from 'react-router-dom/Link';
if all the above stuffs are not needed in your app.

using import() in react-router-dom/webpack2

I googled it but still don't know how to use import() along with react-router-dom (version 4.x) to achieve code-splitting/async-route effect.
I am using webpack2
The doc of react-router-dom use bundle-loader. But I thought import() is supported natively by webpack2. Is there a way to use import() directly?
Thanks
https://github.com/brotzky/code-splitting-react-webpack
https://brotzky.co/blog/code-splitting-react-router-webpack-2/
Checkout this out, I follow the steps and finish dynamic code require for my project.
Anyway, I figure it out myself.
It kind of works at the moment. But I've test it in real world. APPRECIATE to point out bugs in the snippet.
Thanks.
First have a component like this
//#flow
import React from "react";
import { Loading } from "../loading";
let map = {};
export function AsyncLoad(props: {
moduleKey: string,
loadedFrom: Promise<any>,
onLoaded: () => void
}) {
let Comp = map[props.moduleKey];
if (Comp) {
let passedProp = Object.assign({}, props);
delete passedProp.moduleKey;
delete passedProp.loadedFrom;
return <Comp {...props} />;
} else {
processModule();
return <Loading />;
}
async function processModule() {
const mod = await props.loadedFrom;
map[props.moduleKey] = mod.default;
props.onLoaded();
}
}
Then in my App.js, do like this:
//#flow
import React, { PureComponent } from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { AsyncLoad } from "./asyncLoad";
import "./app.scss";
export class App extends PureComponent {
render() {
return (
<Router>
<div>
<Link to="/quiz">Show Quiz</Link>
<div className="content">
<Route
path="/quiz"
component={() =>
<AsyncLoad
moduleKey="quiz"
loadedFrom={import("./quiz")}
onLoaded={() => {
this.forceUpdate();
}}
/>}
/>
</div>
</div>
</Router>
);
}
}
very simple
<Route path="/page3" render={() => (
<AC loader={import('./Page3')} />
)} />
class AC extends Component {
state = {
_: null
}
async componentDidMount() {
const { default: _ } = await this.props.loader;
this.setState({
_: <_ />
});
}
render() {
return (
<div>{this.state._}</div>
);
}
}

<Provider> does not support changing `store` on the fly

I recently began learning how to use React-Native and Redux together. I got an error in the IOS simulator that I can't figure out how to fix, and I was wondering if anyone had seen this before.
Here's the error:
Provider does not support changing store on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/reactjs/react-redux/releases/tag/v2.0.0 for the migration instructions.
I followed that link mentioned in the error message, but it seemed like it needed me to be using Webpack. In the link, where it references if(module.hot), I got the following error when trying to use this solution:
Unable to resolve module
So I'm not sure where to go from here. My project so far is very small. I have my index.ios.js, then an app folder containing a components folder, a store folder and a reducer folder. The structure looks like this:
index.ios.js
app
store
index.js
component
index.js
reducer
index.js
Here is my code:
index.ios.js
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {configureStore} from './app/store';
import Main from './app/components/Main';
export default class introToRedux extends Component {
render() {
return (
<Provider store={configureStore()}>
<Main />
</Provider>
);
}
}
AppRegistry.registerComponent('introToRedux', () => introToRedux);
components/Main.js
import React, { Component } from 'react';
import {connect} from 'react-redux';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
var Main = React.createClass({
render(){
return (
<View>
<Text>{this.props.text}</Text>
</View>
);
}
});
var mapStateToText = (state) => {
return {
text: state.text
}
}
module.exports = connect(mapStateToText)(Main);
reducer/index.js
module.exports = (state={}, action) => {
switch (action.type) {
default:
return state;
}
}
store/index.js
import {createStore} from 'redux';
import reducer from '../reducer';
var defaultState = {
text: "default text"
}
export var configureStore = (initialState=defaultState) => {
return createStore(reducer, initialState);
}
Any help on this would be awesome!
Why do you export configureStore()? You might as well
const initialState = {
text: "default text"
}
export default function reducer (state=initialState, action) {
switch (action.type) {
default:
return state;
}
}
createStore() should be executed once.
index.js
// import stuff
const store = createStore(reducer)
class IntroToRedux extends Component {
render() {
return (
<Provider store={store}>
<Main />
</Provider>
);
}
}
ReactDOM.render(IntroToRedux, document.getElementById('root'))

Problems to dispatch action in React/Redux

I´m pretty new to React and Redux and have some issue during my first steps with it. I tried to follow the examples in the Redux Doc´s, but it´s hard for me to understand everything, because every example is jumping between ES5 - 6 or even 7 syntax.
However, When I try to dispatch an action I got the following error
Uncaught TypeError: (0 , _index2.default) is not a function
Error Message
I know that SO Community doesn´t prefer so much code within one Question, but I don´t know where the problem is coming from. Sorry for that!
These is my Code:
Index.js
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './containers/App'
import configureStore from './store/configureStore'
const store = configureStore()
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
My Store
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import index from '../reducers'
export default function configureStore(preloadedState) {
const store = createStore(
index,
preloadedState,
applyMiddleware(thunkMiddleware, createLogger())
)
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers').default
store.replaceReducer(nextRootReducer)
})
}
return store
}
My Container Component
import React, { Component, PropTypes } from 'react'
import AddTodo from '../components/AddTodo'
import { connect } from 'react-redux'
import addItem from '../actions/index'
class App extends Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
handleClick(e){
console.log("click")
console.log(e);
const {dispatch} = this.props
dispatch(addItem(e));
}
render() {
return (
<div>
< h1 > Hallo </h1>
<AddTodo handleAddItem={this.handleClick}/>
</div>
)
}
}
App.propTypes = {
dispatch: PropTypes.func.isRequired
}
function mapStateToProps(state){
return {
AddTodo
}
}
export default connect (mapStateToProps)(App)
My Child Component:
import React, { Component, PropTypes } from 'react'
import addItem from '../actions/index'
export default class AddTodo extends Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
this.state = {newItem: ''}
}
onChange(e){
console.log("change")
console.log(e.target.value);
this.setState({newItem: e.target.value})
}
handleClick(e){
this.props.handleAddItem(this.state.newItem)
// const {dispatch} = this.props
// console.log("clickc")
// console.log(this.state.newItem);
// dispatch(addItem(this.state.newItem))
}
render() {
return (
<div>
<h3>Add Item </h3>
<input
type="text"
value={this.state.newItem}
onChange={this.onChange.bind(this)}
/>
<button onClick={this.handleClick}>Hallo</button>
</div>
)
}
}
The Reducer
export default (state = [], action) => {
switch (action.type){
case 'ADD_ITEM':
return action.item
}
}
And Finally the action
export function addItem(item){
console.log("addTOdo")
return {
type: 'ADD_ITEM',
item
}
}
I hope someone can help me here, sitting since several hours and don´t understand what is happening.
You are not exporting action creator as default. You need either
export default function addItem(item){
console.log("addTOdo")
return {
type: 'ADD_ITEM',
item
}
}
or
import {addItem} from '../actions/index'

Categories

Resources