React Native FlatList is not showing data from API (axios) - api

I am fairly new to fetching data from an API with React Native, I am using Axios. I'm attempting to fetch categories from an API and list them in a FlatList however it isn't loading on the screen. Here is my code
HomeScreen:
import React from 'react';
import {
View,
Text,
FlatList,
StyleSheet
} from 'react-native';
import ApiData from '../src/api/apiData';
const HomeScreen = () => {
return (
<View>
<FlatList
vertical
data={ApiData.get('/categories')}/>
</View>
);
};
apiData
import axios from 'axios';
export default axios.create({
baseURL:"https://developers.api.com/api/v2.1",
headers: {
'user-key': 'MyKeyGoesHere'
}
})
this is all I've done so far and am a bit lost. Thank you

I updated my code here please check
https://snack.expo.io/SJZC7tJkL

Related

How can I pass params through react-navigation module without navigate to other page?

I am using react-navigation module to implement the bottom tab bar, and now I want to pass the parameters to page B during the operation in page A without page jumping, is there any way to achieve this?
I read the official documentation of react-navigation, and it seems that only the navigation.navigation method can pass parameters across pages, but this will cause page jumps
You can use the AsyncStorage package. Save the data you will use on PageB with a key on PageA. Then get saved data on the PageB.
import React, { useEffect } from 'react';
import { Button } from 'react-native';
import AsyncStorage from '#react-native-async-storage/async-storage';
export default PageA = ({ navigation }) => {
useEffect(() => {
AsyncStorage.setItem("PageParams", "something")
}, [])
return (
<Button title='Navigate' onPress={() => navigation.navigate("PageB")} />
);
};
import { View } from 'react-native';
import React, { useEffect } from 'react';
import AsyncStorage from '#react-native-async-storage/async-storage';
export default PageB = () => {
useEffect(async () => {
const params = await AsyncStorage.getItem("PageParams")
console.log(params) // output: something
})
return (
<View />
);
};

How to fix an Objects are not valid as a React child Error?

I am very new to programming with React-native, and I was wondering if anyone could explain how I should fix this error? I was following along with a tutorial and had an error come up due to this section of code, even though it matched the tutorial code.
Here is the section of code:
import React, { createContext, useContext } from "react";
import * as Google from "expo-google-app-auth";
const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
const signInWithGoogle = async() => {
await Google.logInAsync
}
return (
<AuthContext.Provider
value={{
user: null,
}}
>
{children}
</AuthContext.Provider>
);
};
export default function useAuth() {
return useContext(AuthContext);
}
These other two sections may be relevant as well:
Root of the App:
import React from 'react';
import { Text, View, SafeAreaView, Button, Alert } from 'react-native';
import AuthProvider from "./hooks/useAuth";
import StackNavigator from "./StackNavigator";
import { NavigationContainer} from "#react-navigation/native";
// Function for creating button
export default function App() {
return (
<NavigationContainer>
<AuthProvider>
<StackNavigator />
</AuthProvider>
</NavigationContainer>
);
}
This is my code for the Login Screen:
import React from 'react';
import { View, Text } from 'react-native';
import useAuth from '../hooks/useAuth';
const LoginScreen = () => {
const { user } = useAuth();
console.log(user);
return (
<View>
<Text>
Login to the app
</Text>
</View>
);
};
export default LoginScreen
This is the error that appears:
Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.
I suggest you auth with firebase. it makes easier this things.

useState setmethod is updating inside useEffect but not reflecting the result outside

I was trying to use react-native-contacts library to display my contacts in the app. I am able to establish the connection and name of every person is visible when I do a console.log.
I have created this usestate hook
let [con,setContacts] = useState([])
What I want is to add all the names along with index to this array like this
{name:"adi",index:"1"}
I also did this inside a useEffect hook, but the issue is that when I call console.log(con.length) it prints the total value is 243.When I call the same method outside the useEffect it shows 1. It seems that the usestate is not updating outside.
CODE::
import React, {useState, useEffect} from 'react';
// Import all required component
import {
PermissionsAndroid,
Platform,
SafeAreaView,
StyleSheet,
Text,
View,
FlatList,
TextInput,
} from 'react-native';
import Contacts from 'react-native-contacts';
const ContactScreen = function(){
let [con, setContacts] = useState([]);
//console.log("after usestate")
useEffect(()=>{
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
'title': 'Contacts',
'message': 'This app would like to view your contacts.',
'buttonPositive': 'Please accept bare mortal'
}
)
Contacts.getAll().then(contacts => {
// contacts returned
console.log("heyyyyyy===================")
contacts.map((item,index)=>{
//console.log(item.displayName)
let nobj={name:item.displayName,index:index}
//console.log(nobj)
let arr=con.push(nobj)
//console.log(arr)
setContacts([arr])
console.log(con.length);
//console.log(con);
console.log("=================================================");
})
})
},[])
//issue ==>> displays 1
console.log(con.length);
return(
<View style={style.container}>
<Text>
this is contact screen
</Text>
<Text>{con.length}</Text>
</View>
)
}
const style = StyleSheet.create({
container: {
flex:1,
margin:10,
backgroundColor: '#ebebeb'
}
})
export default ContactScreen;
Output:
output shows that state is updating inside use effect
Hi Firstly you should map the contacts in your designed form. After that when it's mapped then just set the array of contacts in one line. Check out the my following solution.
import React, {useState, useEffect} from 'react';
// Import all required component
import {
PermissionsAndroid,
Platform,
SafeAreaView,
StyleSheet,
Text,
View,
FlatList,
TextInput,
} from 'react-native';
import Contacts from 'react-native-contacts';
const ContactScreen = function(){
let [con, setContacts] = useState([]);
//console.log("after usestate")
useEffect(()=>{
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
'title': 'Contacts',
'message': 'This app would like to view your contacts.',
'buttonPositive': 'Please accept bare mortal'
}
)
Contacts.getAll().then(contacts => {
// contacts returned
const modififiedContacts = contacts.map((item,index)=>{
return {name:item.displayName,index:index}
});
setContacts(modifiedContacts);
})
},[])
//issue ==>> displays 1
console.log(con.length);
return(
<View style={style.container}>
<Text>
this is contact screen
</Text>
<Text>{con.length}</Text>
</View>
)
}
const style = StyleSheet.create({
container: {
flex:1,
margin:10,
backgroundColor: '#ebebeb'
}
})
export default ContactScreen;

Module not found - while adding a component in app.js

I am using React Native. Below is my code in app.js.
import React, { useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Header from './components/Header';
export default function App() {
return (
<View>
</View>
);
}
I made another directory in root and added another js file which is Header.js. It contains below code.
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default function Header() {
return (
<View>
</View>
);
}
I got an error message below.
The development server returned response error code: 500
The module ./components/Header could not be found
Directory Structure
Please let me know if you need more info.
It should be
const Header = () => {
return (
<View>
</View>
);
}
export default Header
Don't just reload an app, restart packager also.
Please correct your functional header component as:
const Header = () => {
return(
<View>.............</View>
)}
export default Header
And run react-native start and react-native run-android
Replace Header component to this:-
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const Header = ({props}) => { // you can also access props like this
return (
<View>
</View>
);
}

Is there any difference between native-base <View/> and react-native <View/>?

I know native-base in a wrapper on react-native library but there are some components which we can import from react-native as well as from native-base also eg., View, Text, etc., Is there any difference between these two imported components. I am new to react native just want to know.
Native Base uses the original react native view and extends it a little bit.
Here is the full code from native base' view:
import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, ViewPropTypes } from "react-native";
import { connectStyle } from "native-base-shoutem-theme";
import mapPropsToStyleNames from "../utils/mapPropsToStyleNames";
class ViewNB extends Component {
render() {
return <View ref={c => (this._root = c)} {...this.props} />;
}
}
ViewNB.propTypes = {
...ViewPropTypes,
style: PropTypes.oneOfType([
PropTypes.object,
PropTypes.number,
PropTypes.array
])
};
const StyledViewNB = connectStyle(
"NativeBase.ViewNB",
{},
mapPropsToStyleNames
)(ViewNB);
export { StyledViewNB as ViewNB };
Source: https://github.com/GeekyAnts/NativeBase/blob/master/src/basic/View.js
I diagnosed more in this and got chain react and kitchen slink which gives more clarity about every component
https://github.com/GeekyAnts/NativeBase