React Native GraphQL nested data array returning error - react-native

I have tried everything I can think of to solve this and am still stumped. I am using AWS AppSync GraphQL to store a dataset that I would like to call into a SectionList.
For the SectionList I am using a hardcoded id to call the data set through a GraphQL query. The SectionList displays correctly when I am using dummy data. It also displays the 1-to-1 relationships in the API correctly.
I already configured amplify to increase the statement depth and I can see the data in the Object.
Code for the SectionList
import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Text, Image, ImageBackground, ScrollView, TouchableOpacity, SectionList, SafeAreaView } from 'react-native';
import Feather from 'react-native-vector-icons/Feather';
import AntDesign from 'react-native-vector-icons/AntDesign';
import { API, graphqlOperation } from 'aws-amplify';
import { getGame, listGameSections, listGames } from '../graphql/queries';
const Item = ({ title }) => (
<View>
<Text>
{title}
</Text>
</View>
);
const GameScreen = ({ navigation }) => {
const [game, setGame] = useState([]);
useEffect(() => {
const fetchGame = async () => {
const gameInfo = { id: '0e2cb273-b535-4cf7-ab16-198c44a4991c'};
if (!gameInfo) {
return;
}
try {
const response = await API.graphql(graphqlOperation(getGame, {id: gameInfo.id}))
setGame(response.data.getGame);
console.log(response);
} catch (e) {
}
};
fetchGame();
}, [])
return (
<SafeAreaView>
<View>
<Text>
{game.name}
</Text>
</View>
<SectionList
sections={game.sections.items}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<View>
<Text>{title}</Text>
</View>
)}>
</SafeAreaView>
)
};
export default GameScreen;
Log of the object.
I am attempting to display the getGame.sections.items array but am returning an error undefined is not an object. Cannot read property items of undefined.
Please help, I am so stumped now. When I call game.name earlier in the function it displays correctly, but game.sections.items throws an error in the SectionList that it is undefined.

Xadm, you pointed me in the right direction. I added this to my code:
const [game, setGame] = useState({});
const [gameSection, setGameSection] = useState([]);
and in my useEffect:
setGameSection(response.data.getGame.sections.items)
When calling the data, game.name wanted an object, while game.sections.items wanted an array for the SectionList. Adding 2 different functions for each initial states, one for the objects and one for the array, was able to fix the problem and render the data.

Related

React Native Async Storage - Cant render value on screen

Hey struggling with this one for a day now.
I am trying to store game data just the gameId and the Level for example Game 1 Level 12
Here is my screen
import React, { Component } from 'react';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { Text, StyleSheet, Button, View, ImageBackground, Pressable } from 'react- native';
import bg from "../assets/images/1.jpg";
import styles from '../assets/style';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
const setScore = async (gameId, level) => {
//// SETS THE SCORE
try {
await AsyncStorage.setItem(scoreKey, level);
console.log(value)
} catch (error) {
console.log(error)
}
};
const getScore = async (gameId) => {
try {
let value = await AsyncStorage.getItem(JSON.stringify(gameId))
if(value !== null) {
// value previously stored
return JSON.stringify(value)
} else {
return "not started"
}
} catch(e) {
// error reading value
}
};
/// This would add game 1 and level 12
setScore('1','12') /// This part works
const theLevel = getScore(1)
export default function Home({navigation, route}) {
return (
<ImageBackground source={bg} resizeMode="cover" style={styles.imageBG}>
<View style={styles.GameList}>
<Text style={styles.mainTitle}>Current Level is {theLevel}</Text>
</View>
</ImageBackground>
);
}
At the bottom of the above code I want to display the level but I get the error
Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection of children, use an array instead.
However If I alert(theLevel) it works fine can someone tell me what I am doing wrong please
Call getScore function from within useEffect hook of your Home component.
export default function Home({ navigation, route }) {
const [level, setLevel] = useState(0);
useEffect(() => {
async function getMyLevel() {
const lvl = await getScore(1);
setLevel(lvl);
}
getMyLevel();
}, []);
const onPress = async () => {
await setScore('1','12');
};
return (
<ImageBackground source={bg} resizeMode="cover" style={styles.imageBG}>
<View style={styles.GameList}>
<Text style={styles.mainTitle}>Current Level is {level}</Text>
</View>
<Button title="Set Score" onPress={onPress} />
</ImageBackground>
);
}

React Native: data not displaying after async fetch

I'm developing a mobile app with React Native and Expo managed workflow. The app is supposed to serve as a song book with lyrics to songs and hymns. All of the lyrics are stored in Firebase' Firestore database and clients can load them in app. I started to implement offline functionality, where all of the lyrics are stored on the user's device using community's AsyncStorage.
I want to get the data stored in AsyncStorage first, set them to state variable holding songs and then look if user has internet access. If yes, I want to check for updates in Firestore, if there were any, I will set the data from Firestore to state variable holding songs. If user does not have internet access, the data from AsyncStorage will already be set to state variable holding songs.
I'm trying to achieve this with an async function inside useEffect hook with empty array of vars/dependecies. The problem I'm having is that no songs are rendered on screen even though they are successfuly retrieved from AsyncStorage.
(When I console.log the output of retrieving the data from AsyncStorage I can see all songs, when I console log songs or allSongs state var, I'm getting undefined)
Here is my simplified code:
import React, { useEffect, useState } from 'react';
import {
StyleSheet,
FlatList,
SafeAreaView,
LogBox,
View,
Text,
} from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { filter, _ } from 'lodash';
import { doc, getDoc } from 'firebase/firestore';
import NetInfo from '#react-native-community/netinfo';
import { db } from '../../../firebase-config';
import { ThemeContext } from '../../util/ThemeManager';
import {
getStoredData,
getStoredObjectData,
storeData,
storeObjectData,
} from '../../util/LocalStorage';
const SongsList = ({ route, navigation }) => {
// const allSongs = props.route.params.data;
const { theme } = React.useContext(ThemeContext);
const [loading, setLoading] = useState(false);
const [allSongs, setAllSongs] = useState();
const [songs, setSongs] = useState(allSongs);
const hymnsRef = doc(db, 'index/hymns');
useEffect(() => {
const setup = async () => {
setLoading(true);
const locData = await getStoredObjectData('hymnsData');
console.log(locData);
setAllSongs(locData);
setSongs(locData);
const netInfo = await NetInfo.fetch();
if (netInfo.isInternetReachable) {
const data = await getDoc(hymnsRef);
const lastChangeDb = data.get('lastChange').valueOf();
const hymnsData = data.get('all');
const lastChangeLocal = await getStoredData('lastChange');
if (lastChangeLocal) {
if (lastChangeLocal !== lastChangeDb) {
await storeData('lastChange', lastChangeDb);
await storeObjectData('hymnsData', hymnsData);
setAllSongs(hymnsData);
setSongs(hymnsData);
}
}
}
sortHymns();
setLoading(false);
};
setup();
}, []);
return (
<SafeAreaView style={[styles.container, styles[`container${theme}`]]}>
{!loading ? (
<FlatList
data={songs}
keyExtractor={(item) => item?.number}
renderItem={({ item }) => {
return <ListItem item={item} onPress={() => goToSong(item)} />;
}}
ItemSeparatorComponent={Separator}
ListHeaderComponent={
route.params.filters ? (
<SearchFilterBar
filters={filters}
handleFilter={handleFilter}
query={query}
handleSearch={handleSearch}
seasonQuery={seasonQuery}
setSeasonQuery={setSeasonQuery}
/>
) : (
<SearchBar handleSearch={handleSearch} query={query} />
)
}
/>
) : (
<View>
<Text>loading</Text>
</View>
)}
<StatusBar style={theme === 'dark' ? 'light' : 'dark'} />
</SafeAreaView>
);
};
export default SongsList;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
The functions getStoredData, getStoredObjectData, storeData and storeObjectData are just getItem and setItem methods of AsyncStorage.
Here is my full code - GitHub.
What am I doing wrong? I've went over many tutorials and articles and it should be working... but I guess not?
Can you check if hymnsData is undefined? After the const hymnsData = data.get('all'); line.
If so, that would explain the issue - you are correctly setting the locData but then overwriting it immediately after. If that is the case, I would add hymnsData to the if condition if (hymnsData && lastChangeLocal) { ... }
If you log songs and allSongs right before the return (, do you see ever see that they are populated, briefly?
Another thing I'd do to debug, is comment out the
setAllSongs(hymnsData);
setSongs(hymnsData);
lines and see if it is working as expected with locData only
The problem was with the sortHymns() method. I moved it from it's own method to the useEffect and it's working now.

React Native: Variable state not updated on first click

I am new in react-native and i am working on an app.
The below code is a simple react-native app which has a custom component with custom events.
But the problem is the variable state is not updated on the first click on the component. But when i click on the second item, The state of the variable is updated.
Please find the code and screenshot below.
App.js
import React, {useState} from 'react';
import { Text, SafeAreaView, ToastAndroid } from 'react-native';
import Dropdown from './components/dropdown';
const app = () => {
const [ itemData, setItemData ] = useState('');
return (
<SafeAreaView style={{ margin: 50 }}>
<Dropdown
onPressItems={(item) => {
ToastAndroid.show('item: ' + item, ToastAndroid.LONG)
setItemData(item)
ToastAndroid.show('setItem: ' + itemData, ToastAndroid.LONG)
}}/>
</SafeAreaView>
);
}
export default app;
Dropdown.js
import React, { useState } from 'react';
import { TouchableOpacity, Text } from 'react-native';
const Dropdown = (props) => {
return (
<TouchableOpacity onPress={() => { props.onPressItems('this is sample data') }}>
<Text>Sample Text</Text>
</TouchableOpacity>
);
}
export default Dropdown;
Screenshot
Code: https://snack.expo.dev/#likithsai/custom-component
Please help me on this issue. Thanks.
useState() hook changes the state asynchronously. so you can't make sure that the state will be changed immediately after calling setItemData() function.
Try useEffect to run a side effect whenever the state changes.
useEffect(() => {
ToastAndroid.show("setItem: " + itemData, ToastAndroid.LONG);
}, [itemData]);
However, this code will show the toast on the component mount. to prevent it try something like this:
const isInitialMount = useRef(true);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
} else {
ToastAndroid.show("setItem: " + itemData, ToastAndroid.LONG);
}
}, [itemData]);
Your code is working just as expected. One of the hooks that are useful to watch for state updates is useEffect. You can add this to your code and see it's working properly:
const app = () => {
const [ itemData, setItemData ] = useState('');
React.useEffect(() => {
console.log('updated itemData:', itemData)
}, [itemData])
return (
<SafeAreaView style={{ margin: 50 }}>
<Dropdown
onPressItems={(item) => {
ToastAndroid.show('item: ' + item, ToastAndroid.LONG)
setItemData(item)
ToastAndroid.show('setItem: ' + itemData, ToastAndroid.LONG)
}}/>
</SafeAreaView>
);
}
You need to take into consideration that useState updates are asynchronous, which means the change won't be reflected immediately.

How to access value calculated in `useEffect` hook from renderer

I am developing a React-Native project with functional component.
Here is a very simple screen which renders a calculated result list. Since I need to calculation to be called only once so I put it inside the useEffect hook.
import {doCalculation} from '../util/helper'
const MyScreen = ({navigation}) => {
useEffect(() => {
// I call a function from a helper module here.
// The result is a list of object.
const result = doCalculation();
// eslint-disable-next-line
}, []);
// renderer
return (
<View>
// Problem is 'result' is not accessible here, but I need to render it here
{result.map(item=> <Text key={item.id}> {item.value} </Text>)}
</View>
)
}
export default MyScreen;
As you can see I have called the doCalculation() to get the result inside useEffect hook. My question is how can I render the result in the return part? Since the result is calculated inside the hook, it is not accessible in the renderer.
P.S. Moving the const result = doCalculation() outside the useEffect hook is not an option since I need the calculation to be called only once.
Below is an example. According to the above comments it looks like you want it to be called once on component mount. All you really need to do is add a useState
import {doCalculation} from '../util/helper'
const MyScreen = ({navigation}) => {
const [calculatedData, setCalculatedData] = useState([])
useEffect(() => {
// I call a function from a helper module here.
// The result is a list of object.
const result = doCalculation();
setCalculatedData(result)
// eslint-disable-next-line
}, []);
// renderer
return (
<View>
// Problem is 'result' is not accessible here, but I need to render it here
{calculatedData.map(item=> <Text key={item.id}> {item.value} </Text>)}
</View>
)
}
export default MyScreen;
const [calculatedData, setCalculatedData] = useState([])
useState is a hook used to store variable state. When calling setCalculatedData inside the useEffect with empty dependency array it will act similar to a componentDidMount() and run only on first mount. If you add variables to the dependency array it will re-run every-time one of those dep. change.
You can change the data inside the calculatedData at anytime by calling setCalculatedData with input data to change to.
Make use of useState to save the calculation result and then use the variable inside return. See https://reactjs.org/docs/hooks-state.html.
Code snippet:
import {doCalculation} from '../util/helper'
const MyScreen = ({navigation}) => {
const [result, setResult] = useState([]);
useEffect(() => {
// I call a function from a helper module here.
// The result is a list of object.
const tempRes = doCalculation();
setResult(tempRes);
// eslint-disable-next-line
}, []);
// renderer
return (
<View>
// Problem is 'result' is not accessible here, but I need to render it here
{result.map(item=> <Text key={item.id}> {item.value} </Text>)}
</View>
)
}
export default MyScreen;
Is async function?
if the function is not async (not wating for respond like from api) - you don't need useEffect.
import React from 'react';
import { Text, View } from 'react-native';
import {doCalculation} from '../util/helper'
const results = doCalculation();
const MyScreen = () => {
return (
<View>
{results.map(item=> <Text key={item.id}> {item.value} </Text>)}
</View>
)
}
export default MyScreen;
else you should wait until the results come from the server..
import React, { useState, useEffect } from 'react';
import { Text, View } from 'react-native';
import { doCalculation } from '../util/helper';
const MyScreen = () => {
const [results, setResults] = useState(null) // or empty array
useEffect(() => {
(async () => {
setResults(await doCalculation());
})();
}, []);
return (
<View>
{results?.map(item => <Text key={item.id}> {item.value} </Text>) || "Loading..."}
</View>
)
}
export default MyScreen;
and I can use more readable code:
if (!results) {
return <View>Loading...</View>
}
return (
<View>
{results.map(item => <Text key={item.id}> {item.value} </Text>)}
</View>
)
the async function can be like:
const doCalculation = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve([{ id: 1, value: 1 }]);
}, 2000);
});
};

Error in viewing item detail and TypeError: Cannot read property 'title' of undefined - Expo React Native

When trying to access the detail of the article, it prints the following error message, adding these lines of code:
13 | return (
14 | <View>
15 | <View>
> 16 | <Text>{article.title}</Text>
| ^ 17 | </View>
18 | </View>
19 | )
List of articles NewsListScreen.js
import React, { useEffect } from 'react';
import { StyleSheet, Text, View, FlatList } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import * as NewsAction from '../redux/actions/NewsAction';
import Card from '../components/Card';
const NewsListScreen = props => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(NewsAction.fetchArticles())
}, [dispatch]);
const articles = useSelector(state => state.news.articles);
console.log(articles);
return (
<FlatList
data={articles}
keyExtractor={item => item.url}
renderItem={({item}) => (
<Card navigation={props.navigation}
title={item.title}
description={item.description}
image={item.urlToImage}
url={item.url}
/>
)}
/>
)
}
const styles = StyleSheet.create ({
});
export default NewsListScreen;
Print item detail NewsItemScreen.js
import React from 'react';
import { StyleSheet, Text, View, Platform, ImageBackground } from 'react-native';
import { useSelector } from 'react-redux';
const NewsItemScreen = props => {
const articleUrl = props.navigation.getParam('articleUrl');
//console.log(articleUrl);
const article = useSelector(state => state.news.articles.find(article => article.url === articleUrl));
//console.log(article);
return (
<View>
<View>
<Text>{article.title}</Text>
</View>
</View>
)
}
const styles = StyleSheet.create ({
});
export default NewsItemScreen;
When I replace this <Text>{article.title}</Text> with <Text>Hello!</Text> it shows the screen printing Hello! with no error.
These articles are the ones that are listed and the ones that are shown in the console correctly, the same ones that I try to see the complete detail, but I get the error message already mentioned.
author: "Megan Rose Dickey"
content: "Hellllooooo, 2021! Welcome back to Human Capital, a weekly newsletter that details the latest in the realms of labor, and diversity and inclusion.
↵Not a ton happened this week so I figured Id use th… [+6204 chars]"
description: "Hellllooooo, 2021! Welcome back to Human Capital, a weekly newsletter that details the latest in the realms of labor, and diversity and inclusion. Not a ton happened this week so I figured I’d use the time to look back on some of the more notable labor storie…"
publishedAt: "2021-01-02T20:00:52Z"
source:
id: "techcrunch"
name: "TechCrunch"
__proto__: Object
title: "Human Capital: The biggest labor stories of 2020"
url: "https://techcrunch.com/2021/01/02/human-capital-the-biggest-labor-stories-of-2020/"
urlToImage: "https://techcrunch.com/wp-content/uploads/2020/08/GettyImages-1142216084.jpg?w=601"
Code Proyect: https://github.com/Publisere/app-news-react
Note: It should be noted that the data does exist, it is not empty data.
Ok well...it seems that article is not defined 😂.
The first time this component is rendered, Article is undefined so you just need to wait (or display a loader, empty page, I let you manage that) before rendering article data.
import React from 'react';
import { StyleSheet, Text, View, Platform, ImageBackground } from 'react-native';
import { useSelector } from 'react-redux';
const NewsItemScreen = props => {
const articleUrl = props.navigation.getParam('articleUrl');
const article = useSelector(state => state.news.articles.find(article => article.url === articleUrl));
if (!article) return null;
return (
<View>
<View>
<Text>{article.title}</Text>
</View>
</View>
)
}
const styles = StyleSheet.create ({
});
export default NewsItemScreen;