Material UI CardMedia is not showing images - javascript

I'm using CardMedia to display images on the screen but it is not showing it.
I have gone through the similar question on Stack Overflow. There the solution give is to import the image and then use it. But here I'm fetching image url from backend using API call.
I have also tried changng heights but it didn't work.
Can anyone explain what is the issue?
import React from "react";
import axios from "axios";
import Card from "#material-ui/core/Card";
import CardHeader from "#material-ui/core/CardHeader";
import CardMedia from "#material-ui/core/CardMedia";
import CardContent from "#material-ui/core/CardContent";
import CircularProgress from "#material-ui/core/CircularProgress";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
root: {
maxWidth: 345,
},
media: {
height: 0,
paddingTop: "56.25%",
},
}));
function ProductList(props) {
const [productList, setProductList] = React.useState([]);
const [loading, setLoading] = React.useState(true);
const classes = useStyles();
const url = `https://api.growcify.com/dev/product/list/${props.listId}`;
const getList = () => {
axios.get(url).then((res) => {
console.log(res.data);
setProductList(res.data);
setLoading(false);
});
};
React.useEffect(() => {
getList();
}, []);
return !loading ? (
productList.length > 0 ? (
productList.map((list) => (
<Card className={classes.root}>
<CardContent>{list.name}</CardContent>
{list.photos.map((img) => {
img !== null && (
<Card className={classes.root}>
{console.log(img)}
<CardMedia
image={img}
component="img"
title="Some title"
className={classes.media}
/>
</Card>
);
})}
</Card>
))
) : (
<h2>No Data Available </h2>
)
) : (
<CircularProgress />
);
}
export default ProductList;
In the provided Screenshot, You can see in the console that I'm getting image url but image is not showing there.

Remove height: 0, from media style

image={"http://localhost:3000/yourPath/"+this.state.your-data.your-variable name}
Dont forget to padding top
Tell me if it works :D

Related

Strange State / UseEffect Behaviour using NextJS Link

I am experiencing so really strange behaviour in this personal project i am doing. In short it is a recipe website, with buttons at the top that direct to different pages that ultimately query firebase and pull down a query.
Index.js File - Queries Firestore passes props to FoodCard.js to Render a list of all recipes
breakfast.js - Queries Firestore with a filter and passes same props down (with different results) to FoodCard.js
Behaviour
When i click on Breakfast JS, it brings up my list of filtered results correctly, however when i click my Next Link "Welcome to the Family Heirloom" to return to the index the first click doesnt respond, then the second click returns home, but with the filtered breakfast result concatonated with all the original results (effectively causing duplicates)Index on First Render
Breakfast filter successful
index with the now duplicate pancake result
I have messed about wondering if useEffect is not getting triggered which you may see in the code, but that didnt seem to work, so at a loss
Index.js
import { React, useEffect, useState } from 'react'
import { useRouter } from 'next/dist/client/router'
import { useTheme } from '#mui/material/styles'
import { makeStyles } from '#mui/styles'
import Modal from '#mui/material/Modal'
import FoodCard from '../src/ui/FoodCard.js'
import firebase from '../firebase/initFirebase'
import Box from '#mui/material/Box'
import Typography from '#mui/material/Typography'
const useStyles = makeStyles(theme => ({
mainContainer: {
}
}))
const style = {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
bgcolor: 'red',
border: '2px solid #000',
boxShadow: 24,
p: 4,
};
export default function CookBook() {
const router = useRouter();
const { id } = router.query;
const classes = useStyles()
const theme = useTheme()
const [loading, setLoading] = useState(true);
const [recipes, setRecipes] = useState([]);
const [open, setOpen] = useState(false);
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
useEffect(() => {
const getRecipesFromFirebase = [];
const subscriber = firebase.firestore()
.collection("recipes")
.onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(querySnapshot)
getRecipesFromFirebase.push({
...doc.data(), //spread operator
key: doc.id, // `id` given to us by Firebase
});
});
setRecipes(getRecipesFromFirebase);
console.log(recipes);
setLoading(false);
});
return () => subscriber();
}, [loading, router.events]); // empty dependencies array => useEffect only called once
if (loading) {
return (
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<Typography id="modal-modal-title" variant="h6" component="h2">
Loading Data
</Typography>
</Box>
</Modal>)
}
return (
<FoodCard recipes={recipes} />
)
}
_app.js
import * as React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import { ThemeProvider } from '#mui/material/styles';
import CssBaseline from '#mui/material/CssBaseline';
import { CacheProvider } from '#emotion/react';
import theme from '../src//ui/theme';
import createEmotionCache from '../src/createEmotionCache';
import Header from '../src/ui/Header';
import Grid from '#mui/material/Grid'
import Typography from '#mui/material/Typography'
import { Link as MUILink } from '#mui/material/'
import NextLink from 'next/link'
// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();
export default function MyApp(props) {
const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
return (
<CacheProvider value={emotionCache}>
<Head>
<meta name="viewport" content="initial-scale=1, width=device-width" />
</Head>
<ThemeProvider theme={theme}>
<Header />
<Grid container justify="center" alignItems="center" direction="column" >
<Grid item>
<NextLink href="/" passHref>
<MUILink underline="none" color="secondary" variant="h1">
Welcome To the Family Heirloom
</MUILink>
</NextLink>
</Grid>
</Grid>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
</CacheProvider>
);
}
MyApp.propTypes = {
Component: PropTypes.elementType.isRequired,
emotionCache: PropTypes.object,
pageProps: PropTypes.object.isRequired,
};
Breakfast.js
import { React, useEffect, useState } from 'react'
import FilterMains from '../../src/ui/FilterMains'
import { useRouter } from 'next/dist/client/router'
import FoodCard from '../../src/ui/FoodCard'
import {
getFirestore, collection, query, where, onSnapshot
} from 'firebase/firestore'
const Breakfast = () => {
const router = useRouter();
const { id } = router.query;
const [breakfastloading, setBreakfastLoading] = useState(true);
const [breakfastRecipe, setBreakfastRecipe] = useState([]);
const db = getFirestore()
const docRef = collection(db, 'recipes')
//Query
const q = query(docRef, where("category", "==", 'Breakfast'))
useEffect(() => {
const getBreakfastFromFirebase = [];
onSnapshot(q, (snapshot) => {
snapshot.docs.forEach((doc) => {
getBreakfastFromFirebase.push({ ...doc.data() })
})
setBreakfastRecipe(getBreakfastFromFirebase)
setBreakfastLoading(false)
console.log(breakfastRecipe)
})
}, [breakfastloading, router.events]);
if (breakfastloading) {
return (
<h2>Loading Data</h2>
)
}
return (
<FoodCard recipes={breakfastRecipe} />
// <FoodCard recipes={recipes} />
)
}
export default Breakfast
FoodCard.js
import React from 'react'
import Card from '#mui/material/Card'
import CardHeader from '#mui/material/CardHeader';
import CardMedia from '#mui/material/CardMedia';
import Grid from '#mui/material/Grid'
import Container from '#mui/material/Container';
import Link from 'next/link'
import CardActionArea from '#mui/material/CardActionArea';
function FoodCard(props) {
return (
<div>
<Container>
< Grid container justify="center" alignItems="center" direction="row" >
<Grid container spacing={2}>
{props.recipes.map((recipe) => (
<Link href={`/recipes/${recipe.key}`} passHref>
<Grid key={recipe.id} item xs={12} md={6}>
<Card elevation={3} sx={{ maxWidth: 400 }}>
<CardActionArea>
<CardHeader
titleTypographyProps={{ fontWeight: "Bold" }}
title={recipe.title}
subheader={recipe.description}
/>
<CardMedia
component="img"
height="194"
image="/assets/comingsoon.jpg"
alt="Mac and Cheese"
/>
</CardActionArea>
</Card>
</Grid>
</Link>
))}
</Grid>
</Grid >
</Container>
</div>
)
}
export default FoodCard
Cracked it, although i can't fully explain why. In my learning i used two different methods for interfacing with firebase. The first method on the index page was what i would call the older way. The second method i used was in all of my other files, specific to interfacing with Version 9 of Firebase.
from this:
const subscriber = firebase.firestore()
.collection("recipes")
.onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(querySnapshot)
getRecipesFromFirebase.push({
...doc.data(), //spread operator
key: doc.id, // `id` given to us by Firebase
});
});
to this:
let getRecipesFromFirebase = [];
getDocs(colRef)
.then((snapshot) => {
let getRecipesFromFirebase = [];
snapshot.docs.forEach((doc) => {
getRecipesFromFirebase.push({ ...doc.data(), key: doc.id })
})
setRecipes(getRecipesFromFirebase);
console.log(recipes);
setLoading(false);
})
.catch(error => {
console.log(error.message)
})
Would love somebody more knowledgable (3 months into React) than myself to tell me as to why though.

Getting a Warning: Each child in a list should have a unique 'key' prop although I already have a key prop in the Grid component from Material-UI

Here is my code below.
Home.js
import { CircularProgress, Container } from '#material-ui/core';
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Posts from "../../components/Posts/Posts";
import { fetchPosts } from '../../redux';
function Home() {
const posts = useSelector(state => state.posts);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchPosts());
}, [dispatch]);
if ((posts && posts.posts.length <= 0) || posts.loading) {
return <CircularProgress />
}
if (posts.posts.posts.length <= 0) {
return <h3>No posts currently.</h3>
}
// handle error here
// maybe use a MUI popup modal
return (
<Container>
<Posts posts={posts.posts.posts} />
</Container>
)
}
export default Home;
Posts.js
import React from 'react';
import { Grid } from "#material-ui/core";
import Post from "../Post/Post";
import useStyles from "./styles";
function Posts({ posts }) {
const classes = useStyles();
return (
<Grid container className={classes.container} spacing={3} >
{posts && posts.map((post) => (
<Grid key={post.id} item xs={12} sm={6} md={6}>
<div className={classes.post}>
<Post
id={post.id}
title={post.title}
content={post.description}
creator={post.creator}
createdAt={post.createdAt}
/>
</div>
</Grid>
))}
</Grid>
)
}
export default Posts;
This is the only place with map() and I've tried adding a key prop to component as well with no luck. I am extremely confused as I remember there weren't any unique key warning earlier until I started fetching the data dynamically (used temporary post object before).

JS React Native - importing local database - with Expo - works only in Web view, not at smartphone

i implemented a little app for learning, and imported data from a local database. I realized it with this code:
import { StatusBar } from 'expo-status-bar';
import { Platform, FlatList, StyleSheet, Text, View, TextInput, Button, SafeAreaView, ScrollView } from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { Icon } from 'react-native-elements'
import * as React from 'react';
import { ListItem, Avatar} from 'react-native-elements';
import { Header } from 'react-native-elements';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { List, Colors } from 'react-native-paper';
import Moment from 'moment';
const MyComponent = () => {
const [expanded, setExpanded] = React.useState(true);
}
const handlePress = () => setExpanded(!expanded);
export default class Db extends React.Component {
state = {
data: [],
}
componentWillMount() { //load data from a remote endpoint (where to instantiate the network request)
this.fetchData();
}
fetchData = async () => {
const response = await fetch('http://localhost:3000/Ph');
const json = await response.json();
this.setState({data: json}); //js object notation
}
keyExtractor = (x, i) => i //extract item
renderItem = ({ item }) => (
<List.Section>
<List.Accordion
theme = {{colors: { primary: '#00A1DE'}}}
style= {{ backgruondColor: '#00A1DE' }}
titleStyle = {styles.titleContainer}
title = {item.Name}
left= { props => <List.Icon {...props} icon = "account" /> }>
<List.Item
titleStyle={styles.textContainer}
title= {item.Geburtsdatum} left= { props => <List.Icon {...props} icon = "cake-variant" /> }></List.Item>
<List.Item
titleStyle={styles.textContainer}
title={item.hobbies} left= { props => <List.Icon {...props} icon = "table-tennis" /> }></List.Item>
</List.Accordion>
</List.Section>
)
render() {
return (
<FlatList
keyExtractor={this.keyExtractor}
data = {this.state.data}
renderItem = { this.renderItem }
/>
)
}
}
const styles = StyleSheet.create({
textContainer: {
flex: 1,
height: '90%',
width: '90%',
},
titleContainer: {
fontWeight: 'bold',
}
});
This works well with the Expo web view, but when I scan the QR Code from my Iphone, the data are not shown. Only footer and header with bottom menue...
I get also the yellow warning because of my ComponentWillMount - function. But do not know, if this is the real reason for my problem. What do you think, why it does not work on my Iphone? I am using the newest expo Version, the newest React Native version and so on... The Code above works well with the Web View from Expo...
Add you IP address instead of localhost
1.) Run cmd
2.) type ipconfig
3.) Scroll Down to IPv4 Address. . . . . . . . . . . : 192.168.**.**
4.) Copy this IP and replace it in place of localhost
5.) Done
Get your IP like this
So Suppose if your IPv4 address is - 192.168.100.84 then
Your fetch should look like this
await fetch('http://192.168.100.84:3000/Ph');
Your component should look like this..Notice I've used Function component here
import * as React from 'react';
import Constants from 'expo-constants';
import { StatusBar } from 'expo-status-bar';
import {
Platform,
FlatList,
StyleSheet,
Text,
View,
TextInput,
Button,
SafeAreaView,
ScrollView,
} from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { Icon } from 'react-native-elements';
import { ListItem, Avatar } from 'react-native-elements';
import { Header } from 'react-native-elements';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { List, Colors } from 'react-native-paper';
import Moment from 'moment';
const BaseURL = '192.168.100.84'; // Here your IPv4 address
export default function App() {
const [Data, setData] = React.useState([]);
React.useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
const response = await fetch(`http://${BaseURL}:3000/Ph`);
const json = await response.json();
setData(json);
};
const keyExtractor = (x, i) => i; //extract item
const renderItem = ({ item }) => (
<List.Section>
<List.Accordion
theme={{ colors: { primary: '#00A1DE' } }}
style={{ backgruondColor: '#00A1DE' }}
titleStyle={styles.titleContainer}
title={item.Name}
left={(props) => <List.Icon {...props} icon="account" />}>
<List.Item
titleStyle={styles.textContainer}
title={item.Geburtsdatum}
left={(props) => (
<List.Icon {...props} icon="cake-variant" />
)}></List.Item>
<List.Item
titleStyle={styles.textContainer}
title={item.hobbies}
left={(props) => (
<List.Icon {...props} icon="table-tennis" />
)}></List.Item>
</List.Accordion>
</List.Section>
);
return (
<FlatList
keyExtractor={keyExtractor}
data={Data}
renderItem={renderItem}
/>
);
}
const styles = StyleSheet.create({
textContainer: {
flex: 1,
height: '90%',
width: '90%',
},
titleContainer: {
fontWeight: 'bold',
},
});

Expo React Native, How to pick default local images or user image obtained from expo image picker

I have a form that a user can select a default local image or an image from the user's photo library
Here is an expo snack use android the images can be found in the phone menu in photos
I want to save either the default local image or user's image to the form and to redux, currently able to save default images picked to form and redux.
This is what currently works.
I have a component that gets a selected local image and returns an image path witch is a number. That local image gets saved in form and in redux. currently, the user can change the local image in the form.
ImgSelector Component:
import React, { useState } from "react";
import { List, Selector, View, SelectedImg } from "./styles";
import { FlatList } from "react-native";
import { defaultImages } from "../../data/defaultImages";
const FlatlistItem = ({ image, setImg }) => {
return (
<Selector onPress={() => setImg(image)}>
<View>
<SelectedImg source={image} />
</View>
</Selector>
);
};
const ImgSelector = ({ setImg }) => {
const [selectedId, setSelectedId] = useState(null);
const renderItem = ({ item }) => (
<FlatlistItem setImg={setImg} image={item.image} />
);
return (
<View>
<FlatList
horizontal
data={defaultImages}
renderItem={renderItem}
keyExtractor={(item, index) => index.toString()}
extraData={selectedId}
/>
</View>
);
};
export default ImgSelector;
Default local images are stored like this and the path is the index which is a number this part works fine.
export const defaultImages = [
{
id: “2”,
image: require("../assets/images/singlepane.png"),
}
]
I have an imagePicker component that asks for permissions and returns a uri string that looks like this:
file:/data/data/host.exp.exponent/cache/ExperienceData/%2540anonymous%252FExpoWcPro-a828b17b-dcd7-4a04-93ca-657c8e4e511d/ImagePicker/6106d73f-c886-457d-abe9-1f1232a0d398.jpg
My form component where images are picked and saved:
import React, { useState } from "react";
import { Image } from "react-native";
const CounterForm = ({ navigation, ...props }) => {
// This is current state for default images that works
const [imgUrl, setImgUrl] = useState(props.imgUrl || defaultImage);
const [userImgUri, setUserImgUri] = useState(null);
// This gets the local image from a componnet
const handleEditImg = (newImgUrl) => {
setImgUrl(newImgUrl);
};
// This gets image uri from expo image picker
const handelUserImg = (userUri) => {
setUserImgUri(userUri);
};
// This sends data to a redux action to save
const handleSubmit = () => {
props.onFormSubmit({
id: props.id,
imgUrl,
});
setImgUrl(defaultImage);
};
return (
<FormWrapper>
<Row>
<FormButton onPress={() => handleSubmit()}>
<StyledText title="Save" color={COLORS.appBlue} />
</FormButton>
</Row>
<TopContent>
{/* I tried this to get user image and displays in form */}
<Image
source={{ uri: userImgUri }}
style={{ width: 100, height: 100 }}
/>
{/* This current implementation gets local images
<Image
source={imgUrl}
style={{ width: 100, height: 100 }}
/> */}
{/* I tried this only gets local images
{imgUrl ? (
<Image source={imgUrl} style={{ width: 100, height: 100 }} />
) : (
<Image
source={{ uri: userImgUri }}
style={{ width: 100, height: 100 }}
/>
)} */}
</TopContent>
<Row>
<ImagePicker getUserImg={handelUserImg} />
</Row>
<View>
<ImgSelector setImg={handleEditImg} />
</View>
</FormWrapper>
);
};
export default CounterForm;
if you use the last sdk version of Expo (40) and the right package expo-image-picker you need to follow this instructions.
First you need to ask for permissions :
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
And then call method to select image from library :
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
So you got image uri by accessing result.uri, you need to save this value (e.g in user store) and display it by selecting your store or default value if there is not stored value :
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Pick an image from camera roll" onPress={pickImage} />
/** imgUrl = stored image uri, defaultImages[0].image = default image uri */
<Image source={imgUrl ? { uri: imgUrl } : defaultImages[0].image} />
</View>
I found the answer it's updated in expo snack
import React, { useState } from "react";
import { List, Selector, View, SelectedImg } from "./styles";
import { FlatList } from "react-native";
import { defaultImages } from "../data";
const FlatlistItem = ({ image, setImg }) => {
return (
<Selector onPress={() => setImg(image)}>
<View>
<SelectedImg source={{uri: image}} />
</View>
</Selector>
);
};
const ImgSelector = ({ setImg }) => {
const [selectedId, setSelectedId] = useState(null);
const renderItem = ({ item }) => {
return (
<FlatlistItem setImg={setImg} image={item} />
)
}
return (
<View>
<FlatList
horizontal
data={defaultImages}
renderItem={renderItem}
keyExtractor={(item, index) => index.toString()}
extraData={selectedId}
/>
</View>
);
};
export default ImgSelector;
Form
import React, { useState } from "react";
import {Asset} from 'expo-asset';
import StyledText from "../UiComponents/StyledText";
import { TouchableWithoutFeedback, Keyboard } from "react-native";
import {
FormWrapper,
TextInputWrapper,
TopContent,
NumberWrapper,
Row,
FormButton,
View,
} from "./styles";
import StyledInput from "../UiComponents/StyledInput";
const defaultImage = Asset.fromModule(require('../assets/komloy.jpg')).uri
import WindowSelector from "../ImgSelector";
import StyledButton from "../UiComponents/StyledButton";
import ImagePicker from "../components/imagePicker";
import { Image } from "react-native";
const DismissKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
const CounterForm = ({ navigation, ...props }) => {
const [imgUrl, setImgUrl] = useState(props.imgUrl || defaultImage);
const handleEditImg = (newImgUrl) => {
setImgUrl(newImgUrl);
};
const handelUserImg = (userUri) => {
setImgUrl(userUri);
};
const handleSubmit = () => {
props.onFormSubmit({
id: props.id,
imgUrl
});
setImgUrl(defaultImage);
};
return (
<DismissKeyboard>
<FormWrapper>
<TopContent>
<Image
source={{uri: imgUrl}}
style={{ width: 100, height: 100 }}
/>
</TopContent>
<Row>
<StyledText title="Select a image" />
<ImagePicker getUserImg={handelUserImg} />
</Row>
<View>
<WindowSelector setImg={handleEditImg} />
</View>
</FormWrapper>
</DismissKeyboard>
);
};
export default CounterForm;
Data
import {Asset} from 'expo-asset';
const imageURI = Asset.fromModule(require('./assets/islands.jpg')).uri
const imageURI2 = Asset.fromModule(require('./assets/maeYai.jpg')).uri
export const defaultImages = [
imageURI, imageURI2
]

How do I use the returned value from the first API call as a parameter to the second API call?

I am trying to make an async API call which will return the adminId.
I want to use the returned value to make a second API call which returns the customer information.
From the code below, for testing purposes, I input the the const adminId as a string but if I were to remove that, how do I pass on the values[0].data.user[0].adminId to the second URL parameter?
import React, { useState, useContext, useEffect } from "react";
import { makeStyles } from "#material-ui/core/styles";
import CssBaseline from "#material-ui/core/CssBaseline";
import AppBar from "#material-ui/core/AppBar";
import Toolbar from "#material-ui/core/Toolbar";
import Typography from "#material-ui/core/Typography";
import IconButton from "#material-ui/core/IconButton";
// import Badge from "#material-ui/core/Badge";
import AccountCircleIcon from "#material-ui/icons/AccountCircle";
// import NotificationsIcon from "#material-ui/icons/Notifications";
import ToggleMenu from "./ToggleMenu";
import axios from "axios";
import AuthApi from "../utils/createContext";
import TablePage from "../components/TablePage";
import FormDialog from "./FormDialog";
import moment from "moment";
const m = moment();
const today = m.format("LL");
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
},
toolbar: {
paddingRight: 24, // keep right padding when drawer closed
},
title: {
flexGrow: 1,
},
appBarSpacer: theme.mixins.toolbar,
content: {
flexGrow: 1,
height: "100vh",
overflow: "auto",
},
}));
export default function Dashboard() {
const classes = useStyles();
const { value } = useContext(AuthApi);
const [userData, setUserData] = useState({});
const readData = async () => {
const adminId = "b581828d-cb7a-483e-9d21-81cbab1606ef";
const fetchUserInfo = await axios.post(`/auth/getemail/${value}`);
const fetchCustomerInfo = await axios.post(
`/customerinfo/getcustomer/${adminId}`
);
Promise.all([fetchUserInfo, fetchCustomerInfo])
// .then((values) => {
// return Promise.all(values);
// })
.then((values) => {
console.log(values[0].data.user[0].adminId);
});
};
useEffect(() => {
readData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<div className={classes.root}>
<CssBaseline />
<AppBar position="absolute">
<Toolbar className={classes.toolbar}>
<Typography
component="h1"
variant="h6"
color="inherit"
noWrap
className={classes.title}
>
Dashboard {today}
</Typography>
<AccountCircleIcon />
<Typography color="inherit" noWrap align="right">
{userData.email}
</Typography>
<IconButton color="inherit">
{/* <Badge badgeContent={4} color="secondary">
<NotificationsIcon />]]]]]'''''
</Badge> */}
</IconButton>
<ToggleMenu />
</Toolbar>
</AppBar>
<main className={classes.content}>
<div className={classes.appBarSpacer} />
{/* <FormDialog adminId={adminId} /> */}
<TablePage />
</main>
</div>
);
}
Simply like this :
const fetchUserInfo = await axios.post(`/auth/getemail/${value}`);
const fetchCustomerInfo = await axios.post(
`/customerinfo/getcustomer/${fetchUserInfo.data.user[0].adminId}`
);
As you are using async await there is no need to Promise.all you are making API calls synchronously.
you can simply do like this if you'll get adminId than and than only second api will call and you'r using await so, remove promises.all().
const fetchUserInfo = await axios.post(`/auth/getemail/${value}`);
let adminId = fetchUserInfo.data.user[0].adminId && fetchUserInfo.data.user[0].adminId;
if (adminId) {
const fetchCustomerInfo = await axios.post(
`/customerinfo/getcustomer/${adminId}`
)
}

Categories