React native custom fonts not loading in, not sure why? - javascript

I did everything like in the documentation, but my Custom Fonts do not want to load in. I could wait for hours and nothing happens...
This is my App.js:
import React, { useState } from 'react';
import AuthNavigation from './AuthNavigation';
import useFonts from './shared/useFonts';
import LoadingScreen from './screens/LoadingScreen';
export default function App() {
const [isReady,setIsReady] = useState(false);
const LoadFonts = async () => {
await useFonts();
setIsReady(true);
}
useEffect(() => {
LoadFonts();
},[])
if (!isReady) {
return(
<LoadingScreen/>
)
}
else{
return (
<AuthNavigation/>
);
}
}
And this is my useFont.js
import Font from 'expo-font';
export default useFont = async () =>
await Font.loadAsync({
QuicksandMedium: require('../assets/Fonts/Quicksand-Medium.ttf'),
AmaticSCRegular: require('../assets/Fonts/AmaticSC-Regular.ttf')
})
There is no error printed in the console, so I have no clue what I am doing wrong :/

I'm not sure, but maybe that if should be the problem. Try with this:
import React, { useState } from 'react';
import AuthNavigation from './AuthNavigation';
import useFonts from './shared/useFonts';
import LoadingScreen from './screens/LoadingScreen';
export default function App() {
const [isReady,setIsReady] = useState(false);
const LoadFonts = async () => {
await useFonts();
setIsReady(true);
};
useEffect(() => {
LoadFonts();
},[]);
return (
<>
{isReady ?
<AuthNavigation/>
:
<LoadingScreen/>
}
</>
);
}

Solution is to import your Fonts like this:
import * as Font from 'expo-font';

Related

createContext undefined

When I try to use createContext() the console gives me this error:
App.js:6
Uncaught TypeError: Cannot destructure property 'consoleLogFunction' of '(0 , react__WEBPACK_IMPORTED_MODULE_1__.useContext)(...)' as it is null.
I've seen others asking questions about this here in Stack Overflow but I can't find a solution.
GlobalContext.js
import React from 'react'
import { createContext } from 'react'
export const AppContext = createContext();
function GlobalContext() {
const consoleLogFunction = () => {
console.log("ok")
}
return (
<AppContext.Provider value={{consoleLogFunction}}></AppContext.Provider>
)
}
export default GlobalContext
App.js
import "./index.css";
import { useContext, useEffect } from "react";
import { AppContext } from "./components/GlobalContext";
function App() {
const { consoleLogFunction } = useContext(AppContext);
useEffect(() => {
consoleLogFunction();
}, []);
return (
<AppContext>
<div>home</div>
</AppContext>
);
}
export default App;
You don't need to export 'AppContext', creating the provider and exporting that is good enough.
Try this, I've also made a couple of modifications to make it easier to use the context later:
GlobalContext.js
import React from 'react'
import { createContext, useContext } from 'react'
const AppContext = createContext();
function GlobalContext({ children }) {
const consoleLogFunction = () => {
console.log("ok")
}
return (
<AppContext.Provider value={{consoleLogFunction}}>
{ children }
</AppContext.Provider>
)
}
export default GlobalContext;
// This is a helper
export const useGlobalContext = () => useContext(AppContext);
Home.js
import { useEffect } from "react";
import { useGlobalContext } from "./components/GlobalContext";
export const Home = ({ children }) => {
const { consoleLogFunction } = useGlobalContext();
useEffect(() => {
consoleLogFunction();
}, []);
return(
<div>home</div>
)
};
App.js
import "./index.css";
import { useEffect } from "react";
import GlobalContext from "./components/GlobalContext"
import { Home } from "./components/Home";
function App() {
return(
<GlobalContext>
<Home />
</GlobalContext>
);
}
export default App;
hello man the problem is because App component is not wrapped inside GlobalContext . and in the GlobalContext component you should handle the children prop.
it will work when doing it like this example :
import { useEffect, useContext, createContext } from "react";
import "./styles.css";
export const AppContext = createContext();
function GlobalContext(props) {
const consoleLogFunction = () => {
console.log("ok");
};
return (
<AppContext.Provider value={{ consoleLogFunction }}>
{props.children}
</AppContext.Provider>
);
}
const Home = () => {
const { consoleLogFunction } = useContext(AppContext);
useEffect(() => {
consoleLogFunction();
}, []);
return <div>home</div>;
};
export default function App() {
return (
<GlobalContext>
<Home />
</GlobalContext>
);
}
Hope this help.

how to dynamically import a react component and call it?

I have a react component that contains an SVG image.
and i import it like this
import MessageIcon from '../static/styles/svg/messageIcon';
However as part of code splitting, i want to dynamically import it instead of static import.
I tried like this but does not work
import('../static/styles/svg/messageIcon').then(MessageIcon => { return <MessageIcon /> });
can anyone tell me how i can dynamically import and call this component? thanks in advance
You can import dynamical like this :
import React, { useEffect, useState } from "react";
const App = () => {
const [state, setState] = useState<any>();
useEffect(() => {
(async () => {
const i = await import("../../assets/img/user.svg");
setState(i);
})();
}, []);
return <img alt={"test dynamic"} src={state?.default} />;
};
export default App;
Also, you can write it with ref too:
import React, { useEffect, useRef } from "react";
const App = () => {
const ref = useRef<any>();
useEffect(() => {
(async () => {
const i = await import("../../assets/img/user.svg");
ref.current.src = i.default;
})();
}, []);
return <img alt={"test dynamic"} ref={ref} />;
};
export default App;
import dynamical React component
import React from "react";
const App = () => {
const nameIcon = "iconMessage";
const IconMessage = React.lazy(() => import(/* webpackChunkName: "icon" */ `./${nameIcon}`));
return <IconMessage />;
};
export default App;

Why does it make a mistake?

The code below is not working. It doesn't see the apikey in parentheses.I couldn't understand what I had to do here. Is it a problem with the hooks structure?
import React, { useEffect } from 'react';
import MovieListing from "../MovieListing/MovieListing";
import movieApi from "../../common/apis/movieApi";
import { APIKey } from "../../common/apis/MovieApiKey"; //the program does not see this
import "./Home.scss";
import { useDispatch } from 'react-redux';
import { addMovies } from '../../features/movies/movieSlice';
const Home = () => {
const dispatch = useDispatch();
useEffect(() => {
const movieText = "Harry";
const fetchMovies = async () => {
const response = await movieApi.get('?apiKey=${APIKey}&s=${movieText}&type=movie')
.catch((err) => { console.log("Err :", err) });
dispatch(addMovies)(response.data); //api key does not see this
};
fetchMovies();
}, []);
return (
<div>
<div className='banner-img'></div>
<MovieListing />
</div>
);
};
export default Home;

React native app is not rendering the component

I am getting this error: error message
Not really sure what I did wrong because everything looks right with my code, at least if I missed something.
import React, { useState } from "react";
import Home from "./screens/home";
import { View } from "react-native";
import * as Font from "expo-font";
import { AppLoading } from "expo-app-loading";
const getFonts = () =>
Font.loadAsync({
"poppins-regular": require("./assets/fonts/Poppins-Regular.ttf"),
"poppins-bold": require("./assets/fonts/Poppins-Bold.ttf"),
});
export default function App() {
const [fontsLoaded, setFontsLoaded] = useState(false);
if (fontsLoaded) {
return <Home />;
} else {
return (
<AppLoading startAsync={getFonts} onFinish={() => setFontsLoaded(true)} />
);
}
}
Can you try changing
import { AppLoading } from "expo-app-loading";
to this:
import AppLoading from 'expo-app-loading';

Export JSON object to another .js without class declaration react-native

I am developing a mobile app which makes GET calls using fetch api. I am stuck in that I am trying to export json object( fetched from server with fetch method) to another .js file to be used as array, But when I import my function in another.js (below), it returns nothing. I tested my fetch method with console so it works as expected, however I am unable to process data in another.js file. By the way, I have searched a lot and found this post Helpful, but not worked.
Below code is implementation of fetch part and exporting it.(Products.js)
import React, { PureComponent,Component } from "react";
import { connect } from "react-redux";
import { View } from "react-native";
import { productsDataSelector } from "../../Products/ProductsSelectors";
import ProductsList from "../../ProductsList/ProductsList";
import Product from "../../Product/Product";
import { NavigationActions, StackActions } from "react-navigation";
import AnotherComponent from "../../Products/ProductsReducer";
class Products extends PureComponent {
render() {
const { navigation } = this.props;
const { productsData } = this.props;
return (
<View>
<ProductsList list={productsData} isSortable>
{product => <Product product={product} />}
</ProductsList>
</View>
);
}
}
const mapStateToProps = state => ({
productsData: productsDataSelector(state)
});
export const getMoviesFromApiAsync = () =>
fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
.then((response) => response.json())
export default connect(
mapStateToProps,
null
) (Products);
Below code is another.js where importing fetch function and processing returning json object without class declaration implemented.
import React, { Component } from "react";
import {getMoviesFromApiAsyncc} from "../screens/Products/Products";
const fakeData = [];
export const someFunc = () => {
fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
.then((response) => response.json())
.then((responseJson) => console.log("responsee:"+JSON.stringify(responseJson)))
.then((responseJson) => {fakeData:JSON.stringify(responseJson)})
.catch((error) => {
console.error(error);
});
};
someFunc();
const initialState = {
data:this.fakeData
};
export default (state = initialState,action) => {
return state;
};
Any recommendations ?? Thanx
I don't see where in your code do you call someFunc and one more thing you need to wrap the object that you return from someFunc in braces otherwise it will be treated as the function's body.
export const someFunc = () => {
getMoviesFromApiAsync().then(response => {
fakeData = JSON.stringify(response)
})
};
someFunc();
I suggest that you move getMoviesFromApiAsync to a separate file and call it from your component to get the list of movies.
api.js
export const getMoviesFromApiAsync = () =>
fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
.then((response) => response.json());
product.js
import React, { PureComponent,Component } from "react";
import { connect } from "react-redux";
import { View } from "react-native";
import { productsDataSelector } from "../../Products/ProductsSelectors";
import ProductsList from "../../ProductsList/ProductsList";
import Product from "../../Product/Product";
import { NavigationActions, StackActions } from "react-navigation";
import AnotherComponent from "../../Products/ProductsReducer";
// import getMoviesFromApiAsync
import { getMoviesFromApiAsync } from 'PATH_TO_API.JS'
class Products extends Component {
async componentDidMount(){
const list = await getMoviesFromApiAsync();
console.log(list);
}
render() {
const { navigation } = this.props;
const { productsData } = this.props;
return (
<View>
<ProductsList list={productsData} isSortable>
{product => <Product product={product} />}
</ProductsList>
</View>
);
}
}

Categories