I have an App from which orders are made to a restaurant.
I need that in the final message that the customer receives, which is sent from the OrderProgress.js file, informing him that his order is ready for collection, the total price of the order is also shown.
The customer selects his products and places the order from the app and a summary of the products and the price of all the products is displayed.
Then the restaurant responds from the Administrator Panel.
When the order is finished by the restaurant, in the administration panel they have a button to mark the order as finished.
When they mark the finished order, it automatically sends a notification to the client's App informing them: **"Your Order is ready. Please can you come and pick it up. Remember that the cost of your meal was: .... "**
Instead of receiving the notification in the App, showing the message and the total price of the order, to pay, I receive an error since it cannot find the variable {total}
The problem I have, I don't know how to import the object that is on the OrderSummary.js screen to the OrderProgress.js screen .
I need that in the final message that the customer receives, which is sent from the OrderProgress.js file, informing him that his order is ready for collection, the total price of the order is also shown.
I must say that I have a State and a Context to communicate the application, but there is something that I have forgotten and the App gives me an error
What should I do to add the total price to the final message that the customer receives?
What am I forgetting?
I show my files, I also show the Context and State
file OrderSummary.js
import React, { useContext, useEffect } from 'react'
import { Alert, ScrollView } from 'react-native'
import {
Container,
List,
ListItem,
Thumbnail,
Text,
Left,
Body,
Button,
H1
} from 'native-base'
import { useNavigation } from '@react-navigation/native'
import globalStyles from '../styles/global'
import firebase from '../firebase'
import PedidoContext from '../context/pedidos/pedidosContext'
const ResumenPedido = () => {
const navigation = useNavigation()
// Context del pedido realizado
const { pedido, total, mostrarResumen, eliminarProducto, pedidoRealizado } = useContext(PedidoContext)
//console.log(pedido)
useEffect(() => {
calcularTotal()
}, [pedido])
// Funcin para iterar sobre el pedido y los productos que añadimos y sus cantidades
const calcularTotal = () => {
let nuevoTotal = 0
nuevoTotal = pedido.reduce((nuevoTotal, articulo) => nuevoTotal + articulo.total, 0)
mostrarResumen(nuevoTotal)
}
// funcion para redirecionar al progreso del pedido
const progresoPedido = () => {
Alert.alert(
'Revise el pedido',
'Una vez realizado el pedido, no podra cambiarlo',
[
{
text: 'Confirmar',
onPress: async () => {
// crear un objeto
const pedidoObjeto = {
tiempoentrega: 0,
completado: false,
total: Number(total),
orden: pedido, //array
creado: Date.now()
}
// console.log(pedidoObjeto)
try {
const pedido = await firebase.db.collection('ordenes').add(pedidoObjeto)
pedidoRealizado(pedido.id)
navigation.navigate("ProgresoPedido")
} catch (error) {
console.log(error)
}
}
},
{ text: 'Revisar', style: 'cancel' }
]
)
}
// Elimina un producto del arreglo de pedido final
const confirmaEliminar = (id) => {
Alert.alert(
'¿Desea eliminar este artículo ... ?',
'Una vez eliminado no podra recuperarlo',
[
{
text: 'Confirmar',
onPress: () => {
// eliminar producto del state
eliminarProducto(id)
}
},
{ text: 'Cancelar', style: 'cancel' }
]
)
}
return (
<Container style={globalStyles.contenedor}>
<ScrollView>
<List>
<H1 style={globalStyles.titulo}>Product Summary</H1>
{pedido.map((plato, i) => {
const { cantidad, nombre, imagen, id, precio } = plato
return (
<List key={id + i}>
<ListItem thumbnail>
<Left>
<Thumbnail large square source={{ uri: imagen }} />
</Left>
<Body>
<Text> {nombre} </Text>
<Text>{cantidad} Units </Text>
<Text> {precio}€ each unit</Text>
<Button
onPress={() => confirmaEliminar(id)}
full
danger
style={{ marginTop: 20 }}
>
<Text style={[globalStyles.botonTexto, { color: '#FFF' }]}>Remove</Text>
</Button>
</Body>
</ListItem>
</List>
)
})}
<Text style={globalStyles.cantidad}>Total to Pay:{total} €</Text>
<Button
onPress={() => navigation.navigate('Menu')}
style={{ marginTop: 20 }}
full
rounded
dark
>
<Text style={[globalStyles.botonTexto, { color: '#FFF' }]}>Keep Shopping</Text>
</Button>
<Button
onPress={() => progresoPedido()}
style={globalStyles.botonForm}
full
>
<Text style={globalStyles.botonTexto}>Ordering</Text>
</Button>
</List>
</ScrollView>
</Container>
)
}
export default ResumenPedido
file OrderProgress.js
import React, { useContext, useEffect, useState } from 'react'
import { StyleSheet, View } from 'react-native'
import { Container, Button, Text, H1, H3 } from 'native-base'
import globalStyles from '../styles/global'
import { useNavigation } from '@react-navigation/native'
import PedidoContext from '../context/pedidos/pedidosContext'
import ResumenPedido from './ResumenPedido' import firebase from '../firebase'
import Countdown from 'react-countdown'
const ProgresoPedido = () => {
const navigation = useNavigation()
const { idpedido, total } = useContext(PedidoContext)
const [tiempo, guardarTiempo] = useState(0)
const [completado, guardarCompletado] = useState(false)
useEffect(() => {
const obtenerProducto = () => {
firebase.db.collection('ordenes')
.doc(idpedido)
.onSnapshot(function(doc) {
guardarTiempo(doc.data().tiempoentrega)
guardarCompletado(doc.data().completado)
})
}
obtenerProducto()
}, [])
// Muestra el tiempo en pantalla con Countdown
const renderer = ({ minutes, seconds }) => {
return (
<Text style={styles.tiempo}>{minutes}:{seconds}</Text>
)
}
return (
<Container style={globalStyles.contenedor}>
<View style={[globalStyles.contenido, { marginTop: 50 }]}>
{tiempo === 0 && (
<>
<Text style={{ textAlign: 'center', fontSize: 24 }}>We have received your Order ... </Text>
<Text style={{ textAlign: 'center', fontSize: 24 }}>We are calculating the delivery time</Text>
</>
)}
{!completado && tiempo > 0 && (
<>
<Text style={{ textAlign: 'center' }}> Your order will be ready in:</Text>
<Text>
<Countdown
date={Date.now() + tiempo * 60000}
renderer={renderer} //muestra el tiempo que queda del pedido en la pantalla
/>
</Text>
</>
)}
{completado && (
<>
<H1 style={styles.textoCompletado}>Your order is ready</H1>
<H3 style={styles.textoCompletado}>Please can you come and pick it up.</H3>
<Text style={[styles.textoComplPrecio, {marginVertical: 40}]}>Remember what cost of your meal was: {total} </Text>
<Button tyle={ [globalStyles.boton, {marginTop:200}]}
rounded
block
onPress={ () => navigation.navigate("NuevaOrden")}
>
<Text style={ globalStyles.botonTexto}>Exit to Menu</Text>
</Button>
</>
)}
</View>
</Container>
)
}
const styles = StyleSheet.create({
tiempo: {
marginBottom: 20,
fontSize: 60,
textAlign: 'center',
marginTop: 80,
},
textoCompletado: {
textAlign: 'center',
textTransform: 'uppercase',
marginBottom: 20
},
textoComplPrecio: {
textAlign: 'center',
fontSize: 24,
color: '#8E44AD'
}
})
export default ProgresoPedido
file stateOrders.js
import React, { useReducer } from 'react'
import PedidoReducer from './pedidosReducer'
import PedidoContext from './pedidosContext'
import {
SELECCIONAR_PRODUCTO,
CONFIRMAR_ORDENAR_PLATO,
MOSTRAR_RESUMEN,
ELIMINAR_PRODUCTO,
PEDIDO_ORDENADO
} from '../../types'
const PedidosState = props => {
// Create initial state const initialState = {
pedido: [],
plato: null,
total: 0,
idpedido: ''
}
// useReducer with dispatch to execute functions const [state, dispatch] = useReducer(PedidoReducer, initialState)
// Select the Product that the user wants to order const selecionarPlato = plato => {
dispatch({
type: SELECCIONAR_PRODUCTO,
payload: plato
})
}
// when the user confirms an order const guardarPedido = pedido => {
dispatch({
type: CONFIRMAR_ORDENAR_PLATO,
payload: pedido
})
}
// Shows the total to pay in the summary of each item const mostrarResumen = total => {
dispatch({
type: MOSTRAR_RESUMEN,
payload: total
})
}
// Delete the selected item from the shopping cart const eliminarProducto = id => {
dispatch({
type: ELIMINAR_PRODUCTO,
payload: id
})
}
const pedidoRealizado = id => {
dispatch({
type: PEDIDO_ORDENADO,
payload: id
})
}
return (
<PedidoContext.Provider
value={{
pedido: state.pedido,
plato: state.plato,
total: state.total,
idpedido: state.idpedido,
selecionarPlato,
guardarPedido,
mostrarResumen,
eliminarProducto,
pedidoRealizado
}}
>
{props.children}
</PedidoContext.Provider>
)
}
export default PedidosState
