'React UseEffect api calls mapping arrays
I am fetching two object arrays from api backend and joined by id if exists, all of them in useEffect.
I am confusing, cause if write "console.log" whole info is on screen but if comment or delete console cant watch nothing on screen.
Any help?
Using react and material
import React, { useState, useEffect, useRef } from "react";
import { useAuth } from "../../contexts/Auth";
import { supabase } from "../../lib/supabase";
import {
Avatar,
Grid,
Container,
Typography,
Button,
Box,
} from "@mui/material";
import { createTheme, ThemeProvider, styled } from "@mui/material/styles";
const HiklubTheme = createTheme({
palette: {
primary: {
main: "#7c378a",
},
secondary: {
main: "#93c01f",
},
},
});
const StyledAffinityTypo = styled(
Typography,
{}
)({
color: "white",
backgroundColor: "#93c01f",
padding: "0.5rem",
maxWidth: "100%",
fontFamily: ["Asap"],
});
const StyledKluberAvatar = styled(
Avatar,
{}
)({
width: "4rem",
height: "4rem",
objectFit: "contain",
});
export default function ListCustomerBooked({ id }) {
const { user } = useAuth();
const [loading, setLoading] = useState(true);
const [customers, setCustomers] = useState([]);
const [scores, setScores] = useState([]);
const [CustomerScore, setCustomerScore] = useState([]);
useEffect(() => {
async function fetchCustomer(id) {
try {
setLoading(true);
let { data, error, status } = await supabase
.from("customers")
.select("*")
.eq("customer", id);
if (error && status !== 406) {
throw error;
}
if (data) {
// remove customer from array
data = data.filter((el) => el.customers.id !== user.id);
const items = data.map((object) => ({
token: object.token,
customer_id: object.id,
email: object.email,
firstname: object.firstname,
}));
setCustomers(items);
}
} catch (error) {
alert(error.message);
} finally {
setLoading(false);
}
}
async function fetchCustomerScores() {
try {
setLoading(true);
let { data, error, status } = await supabase
.from("scores")
.select("*")
.eq("customer_id", user.id);
if (error && status !== 406) {
throw error;
}
setScores((scores) => [...scores, ...data]);
} catch (error) {
alert(error.message);
} finally {
setLoading(false);
}
}
fetchCustomer(id);
fetchCustomerScores();
// Map two arrays and add score
setCustomerScore(
customers.map((t1) => ({
...t1,
...scores.find((t2) => t2.customer_id === t1.customer_id ),
}))
);
}, [id]);
return (
<Container sx={{ my: "2rem" }}>
<Grid container>
<Grid item>
<Typography variant="h5" sx={{ fontWeight: "bold", my: "1rem" }}>
{" "}
Count customers ({customers.length + 1}){" "}
</Typography>
</Grid>
</Grid>
<Grid container sx={{ my: "3rem" }}>
{CustomerScore.map((customer, index) => (
<Grid key={index} item xs={3}>
<ThemeProvider theme={HiklubTheme}>
<StyledKluberAvatar
alt={customer.email}
color="secondary"
src="https://images.unsplash.com/photo-1542740348-39501cd6e2b4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80"
></StyledKluberAvatar>
</ThemeProvider>
{!customer.score ? (
<Typography sx={{ fontWeight: "light" }}>
No customer's score
</Typography>
) : (
<Typography sx={{ fontWeight: "light" }}>
{parseFloat(customer.score).toFixed(0)} %
</Typography>
)}
<ThemeProvider theme={HiklubTheme}>
{!customer.firstname ? (
<Typography sx={{ fontWeight: "light" }}>
{customer.firstname}
</Typography>
) : (
<Typography sx={{ fontWeight: "bold" }}>
{customer.email}
</Typography>
)}
</ThemeProvider>
</Grid>
))}
</Grid>
</Container>
);
}
Not rendering on screen,
Thanks to all
Solution 1:[1]
As fetchCustomer and fetchCustomerScores are async
try
async function loadData() {
await fetchCustomer(id);
await fetchCustomerScores();
// Map two arrays and add score
setCustomerScore(
customers.map((t1) => ({
...t1,
...scores.find((t2) => t2.customer_id === t1.customer_id ),
}))
);
}
loadData();
in place of
fetchCustomer(id);
fetchCustomerScores();
// Map two arrays and add score
setCustomerScore(
customers.map((t1) => ({
...t1,
...scores.find((t2) => t2.customer_id === t1.customer_id ),
}))
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kranthi |
