The icon disappears and null in my terminal - javascript

I updated my code thanks to your help. When I launch the app with Expo, I have two errors:
1/ I lost my scan icon which does not appear in my screen. This icon appeared previously. The idea is to scan some barcodes in order to display relevant data stemming from products.
2/ In my terminal, when the app is launched with Expo, I have this message: Array[], null, null
I would appreciate your comments concerning my issues. All the best,
Here is my new code:
import React, { useState, useEffect } from "react";
import {
StyleSheet,
Text,
View,
FlatList,
Button,
AsyncStorage,
} from "react-native";
import { useNavigation } from "#react-navigation/core";
import { TouchableOpacity } from "react-native-gesture-handler";
import { FontAwesome5 } from "#expo/vector-icons";
import { MaterialCommunityIcons } from "#expo/vector-icons";
import { ActivityIndicator } from "react-native-paper";
function ProductsScreen() {
const navigation = useNavigation();
const [data, setData] = useState([]);
const [isLoading, setisLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const data = await AsyncStorage.getItem("userData");
setData(data);
setisLoading(false);
};
fetchData();
}, []);
console.log(data);
return isLoading ? (
<ActivityIndicator />
) : (
<>
{data ? (
<FlatList
data={dataArray}
keyExtractor={(item) => item.name}
renderItem={({ item }) => (
<>
<Text>{item.brand}</Text>
<View style={styles.scan}>
<MaterialCommunityIcons
name="barcode-scan"
size={40}
color="black"
onPress={() => {
navigation.navigate("CameraScreen");
}}
/>
</View>
</>
)}
/>
) : null}
</>
);
}
export default ProductsScreen;

Can you explain a little more? Having trouble making Asyncstroge setItem? If the vector icon is not visible,
react-native run-android,
You can try doing npm start --reset-cache.

Related

Error: Element type is invalid: expected a string | Native Base | React Native

I have a component that was working just fine until I started using the native-base library in React native. I'm being thrown the error element type invalid, saying that there's something wrong with the export but I can't see what the problem is
Here's the code
import {
StyleSheet,
View,
// Text,
FlatList,
} from "react-native";
import React, { useEffect, useState } from "react";
import {
Container,
Header,
Icon,
Item,
Input,
Text,
NativeBaseProvider,
Box,
} from "native-base";
// const data = require("");
import data from "../../assets/data/products.json";
import ProductList from "./ProductList";
const ProductContainer = () => {
const [products, setProducts] = useState([]);
const [productsFiltered, setProductsFiltered] = useState([]);
useEffect(() => {
setProducts(data);
setProductsFiltered(data);
return () => {
setProducts([]);
};
}, []);
return (
<NativeBaseProvider>
<Container>
<Header searchBar rounded>
<Item>
<Icon name="ios-search" />
<Input placeholder="Search" />
</Item>
<Icon name="ios-people" />
</Header>
<View style={styles.container}>
<View style={styles.listContainer}>
<FlatList
horizontal
data={products}
renderItem={({ item }) => (
<ProductList key={item.id} item={item} />
)}
keyExtractor={(item) => item.name}
/>
</View>
</View>
</Container>
</NativeBaseProvider>
);
};
export default ProductContainer;
const styles = StyleSheet.create({
container: {
},
listContainer: {
},
center: {
},
});

React Navigation not passing props

I have a component that takes an object and passes it to a new screen upon navigating to the screen. However, when I go to the next screen the object passed is undefined. What am I doing wrong here? I have done the exact same thing with another component and it works perfectly fine, but on this component, it isn't passing the parameter properly. Is there something else I need to configure in the navigator?
GoalCard.JS
import * as React from 'react';
import 'react-native-get-random-values';
import { v4 as uuidv4 } from 'uuid';
import { useNavigation } from "#react-navigation/core";
import { Card, Chip, Divider, Paragraph, Text, Title } from 'react-native-paper';
const GoalCard = ({ item }) => {
const navigation = useNavigation();
const goals = JSON.parse(item.Goals);
const tasks = JSON.parse(item.GoalTasks);
const [goalsData, setGoalsData] = React.useState(
{
GoalName: item.GoalName,
GoalID: item.GoalID,
GoalDescription: item.GoalDescription,
GoalComplete: item.GoalComplete,
GoalTasks: tasks,
Goals: goals,
UserID: item.UserID,
createdAt: item.createdAt,
updatedAt: item.updatedAt
}
);
return(
<Card className="card">
<Card.Content>
<Title>Goal Set: {item.GoalName}</Title>
<Divider/>
<Paragraph>
<Chip
onPress={() => {
navigation.navigate(
'Goals', {
goalsData: goalsData
});
}}
>
Edit
</Chip>
<Text onPress={() => console.log(goalsData)}>Log</Text>
<Text>Description: {item.GoalDescription}</Text>
<Divider/>
{Object.entries(goals).map(obj => (
<Text key={uuidv4()}>{obj[1].goal}{" "}</Text>
))}
</Paragraph>
</Card.Content>
</Card>
);
}
export default GoalCard;
GoalScreen.js
Pressing "Log" as seen in this file returns undefined
import React from "react";
import { ScrollView, View } from "react-native";
import { Text } from "react-native-paper";
import { MainStyles } from "../../styles/Styles";
const GoalScreen = ({ route }) => {
const { goalData } = route.params;
return (
<ScrollView>
<View style={MainStyles.col}>
<Text onPress={() => console.log(goalData)}>Log</Text>
</View>
</ScrollView>
);
};
export default GoalScreen;
There is a typo ... You are setting
goalsData: goalsData
But you are trying to read as below
const { goalData } = route.params;
try
const { goalsData } = route.params;

Not sure how to include function in useEffect

I am trying to mount a function within useEffect, how would I call this function within useEffect, I am not sure?
Initially useEffect is written as following in the app-
useEffect(() => {
CognitensorEndpoints.getDashboardList({
dispatchReducer: dispatchDashboards,
});
CognitensorEndpoints.getList({
dispatchReducer: dispatchDashboards,
});
},[]);
Then when I include useEffect as below, it returns errors ('Cannot read property 'filter' of undefined') -
useEffect(() => {
console.log('abcd');
setLoading();
CognitensorEndpoints.getDashboardList({
dispatchReducer: dispatchDashboards,
});
CognitensorEndpoints.getList({
dispatchReducer: dispatchDashboards,
});
},[]);
How do I correctly include 'setLoading()' within useEffect?
Here's the full app code-
import React, { useState, useEffect, useReducer } from 'react';
import { View, Text, StyleSheet, FlatList, ActivityIndicator, Keyboard, Button } from 'react-native';
import { Searchbar } from 'react-native-paper';
import { theme } from '../theme';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { apiStateReducer } from '../reducers/ApiStateReducer';
import CognitensorEndpoints from '../services/network/CognitensorEndpoints';
import DefaultView from '../components/default/DefaultView';
import DashboardListCard from '../components/DashboardListCard';
import DashboardHeader from '../components/DashboardHeader';
import DashboardGridCard from '../components/DashboardGridCard';
import {
NavigationContainer,
useFocusEffect,
} from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
const AppHeader = ({
scene,
previous,
navigation,
searchIconVisible = false,
item,
index,
onPress
}) => {
const [dashboards, dispatchDashboards] = useReducer(apiStateReducer, {
data: [],
isLoading: true,
isError: false,
});
const [gridView, setGridView] = useState(false);
const toggleGridView = () => {
setGridView(!gridView);
};
const [filtered, setFiltered] = useState([]);
const setLoading = () => {
const messages = dashboards.data.message.filter((item) => {
const title = item.dashboardTitle || item.dashboardName;
return title.toLowerCase();
});
setFiltered(messages);
console.log(filtered);
};
const dropShadowStyle = styles.dropShadow;
const toggleSearchVisibility = () => {
navigation.navigate('Search');
};
useEffect(() => {
console.log(abcd);
setLoading();
CognitensorEndpoints.getDashboardList({
dispatchReducer: dispatchDashboards,
});
CognitensorEndpoints.getList({
dispatchReducer: dispatchDashboards,
});
},[]);
return (
<>
<View style={styles.header}>
<View style={styles.headerLeftIcon}>
<TouchableOpacity onPress={navigation.pop}>
{previous ? (
<MaterialIcons
name="chevron-left"
size={24}
style={styles.visible}
/>
) : (
<MaterialIcons
name="chevron-left"
size={24}
style={styles.invisible}
/>
)}
</TouchableOpacity>
</View>
{filtered.map(item => (
<Text style={styles.headerText}>
{item.dashboardTitle}
</Text>
))}
<View style={styles.headerRightIconContainer}>
{searchIconVisible ? (
<TouchableOpacity
style={[styles.headerRightIcon, dropShadowStyle]}
onPress={toggleSearchVisibility}>
<MaterialIcons name="search" size={24} style={styles.visible} />
</TouchableOpacity>
) : (
<View style={styles.invisible} />
)}
</View>
</View>
</>
);
};
The error is because dashboards.data.message is undefined or null. Please re-check the data.

What could be the cause when the API populates in Console but fails to populate in frontend?

I am new to react and have tried to following various tutorials however i am stuck at this point and just sure something silly is just the cause. I can't get the data to display in frontend. My API works fine on Postman and is Django Rest Framework- made. The data populates to console. Below is the code 1.Note.js 2. App published Notes 3. App.js 4. Note Model :
import React from 'react';
import { Box, Flex } from '#chakra-ui/core';
import NoteDetail from './NoteDetail';
export default function Note({ note }) {
return (
<Flex
align="center"
justify="flex-end"
direction="column"
bg="teal"
width="300px"
height="300px"
borderRadius="40px"
margin="16px"
padding="16px"
>
<Box as="button" size="144px" bg="white" color="teal" textAlign="center" isTruncated>
{note.title}
<Box as="span">{note.display_name}</Box>
<NoteDetail note={note} key={note.pk} />
</Box>
</Flex>
);
}
import React, { useState, useEffect } from 'react';
import { Flex } from '#chakra-ui/core';
import axios from 'axios';
import Error from './Error';
import Loading from './Loading';
import Note from './Note';
export default function AllPublishedNotes() {
const [data, setData] = useState([]);
const [isError, setIsError] = useState(false);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const allPublished = async () => {
setIsError(false);
setIsLoading(true);
try {
const result = await axios.get('http://localhost:8000/api/note/published_notes/');
setData(result.data);
console.log(result.data);
} catch (error) {
setIsLoading(false);
setIsError(true);
}
};
allPublished();
}, []);
const noData = !data;
return (
<>
<Flex
justify="center"
align="center"
flexWrap="wrap"
flexDirection={noData ? 'column' : 'row'}
margin="16px"
padding="16px"
>
{isLoading && !isError ? (
<Loading />
) : isError ? (
<Error />
) : (
data.map((note) => <Note key={note.pk} note={note} />)
)}
</Flex>
</>
);
}
import React from 'react';
import { ThemeProvider, CSSReset, theme } from '#chakra-ui/core';
import AllPublishedNotes from './component/AllPublishedNotes';
export default function App() {
return (
<>
<ThemeProvider theme={theme}>
<CSSReset />
<AllPublishedNotes />
</ThemeProvider>
</>
);
}
from django.db import models
from django.conf import settings
class Note(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(max_length=500)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE )
is_published = models.BooleanField(default=False)
date_created = models.DateTimeField(auto_now_add=True)
date_published = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
Somebody please help look through what the issue could be. Not necessary you use Chakra just need to know what went wrong with my react code itself
by the answer here you can debug it by opening django/apps/registry.py and around line 80
raise RuntimeError("populate() isn't reentrant")
replace with:
self.app_configs = {}
I have updated the code. Please try the following code.
axios.get(`http://localhost:8000/api/note/published_notes`)
.then(res => {
console.log(res);
})

Too many re-renders on search API

I am new to this so I hope this is the right place to get help!
As titled, executing this code is giving me the "Too many re-renders" error on React.
I have tried going through all lines and checking my hooks repeatedly, but nothing seems to work.
I am guessing this is happening due to useEffect, so pasting the code for the relevant components below:
UseResults:
import { useEffect, useState } from 'react';
import yelp from '../api/yelp';
export default () => {
const [results, setResults] = useState([]);
const [errorMessage, setErrorMessage] = useState('');
const searchApi = async () => {
try {
const response = await yelp.get('/search', {
params: {
limit: 50,
term,
location: 'san francisco'
}
});
setResults(response.data.businesses);
} catch (err) {
setErrorMessage('Something went wrong')
}
};
useEffect(() => {
searchApi('pasta');
}, []);
return [searchApi, results, errorMessage];
}
SearchScreen:
import React, { useState } from 'react';
import { Text, StyleSheet } from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';
import ResultsList from '../components/ResultsList';
import SearchBar from '../components/SearchBar';
import useResults from '../hooks/useResults';
const SearchScreen = (navigation) => {
const [term, setTerm] = useState('');
const [searchApi, results, errorMessage] = useResults();
const filterResultsByPrice = (price) => {
return results.filter(result => {
return result.price === price;
});
};
return <>
<SearchBar
term={term}
onTermChange={setTerm}
onTermSubmit={searchApi()}
/>
{errorMessage ? <Text>{errorMessage}</Text> : null}
<Text>We have found {results.length} results</Text>
<ScrollView>
<ResultsList
results={filterResultsByPrice('$')}
title="Cost Effective"
navigation={navigation}
/>
<ResultsList
results={filterResultsByPrice('$$')}
title="Bit Pricier"
navigation={navigation}
/>
<ResultsList
results={filterResultsByPrice('$$$')}
title="Big Spender"
navigation={navigation}
/>
</ScrollView>
</>
};
const styles = StyleSheet.create({});
export default SearchScreen;
ResultsList:
import React from 'react';
import { View, Text, StyleSheet, FlatList } from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import ResultsDetail from './ResultsDetail';
const ResultsList = ({ title, results, navigation }) => {
return (
<View style={styles.container} >
<Text style={styles.title}>{title}</Text>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={results}
keyExtractor={result => result.id}
renderItem={({ item }) => {
return (
<TouchableOpacity onPress={() => navigation.navigate('ResultsShow')}>
<ResultsDetail result={item} />
</TouchableOpacity>
)
}}
/>
</View>
);
};
const styles = StyleSheet.create({
title: {
fontSize: 18,
fontWeight: 'bold',
marginLeft: 15,
marginBottom: 5
},
container: {
marginBottom: 10
}
});
export default ResultsList;
TIA!

Categories

Resources