const newState = {...state};
^^^ SyntaxError: Unexpected token ...
I am getting the above error when I tried a simple redux program to increment age.
The piece of code is as follows:
const {createStore} = require('redux');
const initialState ={
age : 21
}
const myReducer = (state = initialState, action) =>{
const newState = {...state};
if(action.type === 'ADD')
newState.age +=1;
return newState;
}
const store = createStore(myReducer);
store.dispatch({type : 'ADD'})
console.log(store.getState());
Related
Hello I am trying to integrate stripe payment method in react native app everything work fine except for last step in which presentPaymentSheet has to dismiss and payment should be successfull in stripe account but it says incomplete in stripe account.
Client Side Code
const { initPaymentSheet, presentPaymentSheet } = useStripe();
const { paymentIntent, ephemeralKey, customer } =
await fetchPaymentSheetParams();
const { error } = await initPaymentSheet({
customerId: customer,
customerEphemeralKeySecret: ephemeralKey,
paymentIntentClientSecret: paymentIntent.client_secret,
});
if (!error) {
setPaymentSheetEnabled(true);
}
const openPaymentSheet = async () => {
if (!clientSecret) {
return;
}
setLoading(true);
const { error } = await presentPaymentSheet();
console.log({error});
}
Server Side Code
const functions = require("firebase-functions");
const stripe = require("stripe")(functions.config().stripe.secret);
console.log(stripe);
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.paymentSheet = functions.https.onRequest(async (req, res) => {
const db = admin.firestore();
const uid = db.collection("place_order").doc("id");
const id = await uid.get();
const cityRef = db.collection("orders").doc(id.data().id);
const doc = await cityRef.get();
const price = doc.data().order;
const code = db.collection("settings").doc("currency");
const currencyCode = await code.get();
const cCode = currencyCode.data().code;
const customer = await stripe.customers.create();
const ephemeralKey = await stripe.ephemeralKeys.create(
{customer: customer.id},
{apiVersion: "2022-08-01"},
);
const paymentIntent = await stripe.paymentIntents.create({
amount: price[price.length - 1].order_data[0].price * 100,
currency: cCode,
customer: customer.id,
automatic_payment_methods: {
enabled: true,
},
});
res.json({
paymentIntent: paymentIntent,
ephemeralKey: ephemeralKey.secret,
customer: customer.id,
});
});
When trying to get data in next js, the server does not return anything at all, the console is empty, tell me, please, what could be wrong?
export const getStaticProps = async () => {
const res = await fetch('https://api.jikan.moe/v4/top/manga');
const data = await res.json();
console.log('data >>>', data);
return {
props: {
manga: data,
},
};
};
When I follow other Firebase authentication tutorials, even if I have logged in my app from a device before, it still wouldn't automatically log me in the second time I open it. I then tried to set the persistence following this guide, but the error occurred that looks like this (screenshot provided below).
undefined is not an object (evaluating 'this.storage.setItem')
the screenshot of the error message
Anyways, here's the code for the login page:
import React, {useEffect, useState} from "react";
import {
// A bunch of other components,
TouchableOpacity,
} from "react-native";
import firebase from "firebase/compat";
import {auth} from "./firebase";
// code in "./firebase.js" is as follows:
// import "firebase/compat/auth";
// const auth = firebase.auth();
const LoginScreen = ({ navigation }) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [user, setUser] = useState();
const [initializing, setInitializing] = useState(true);
const handleAuthStateChange = (user) => {
setUser(user);
if (!initializing) setInitializing(false);
}
useEffect(() => {
const userReturn = auth.onAuthStateChanged(handleAuthStateChange);
return userReturn;
}, []);
if (user) {
navigation.navigate("Main");
}
const handleLogin = () => {
if (email !== "" && password !== "") {
auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(() => {
return auth.signInWithEmailAndPassword(email, password);
})
.catch(error => alert(error.message))
}
}
return (
// Some UI stuff...
<TouchableOpacity onPress={handleLogin}>
<Text>Login</Text>
</TouchableOpacity>
// Other UI stuff...
)
}
export default LoginScreen;
I'd managed to get some of my earlier functions state in devtools as below:
Reducers function in DevTools
But when I tried to query some of the events in my interactions, the functions state werent able to display it. Below are my codes and settings, basically the flow is interactions > actions > reducers
interaction code:
export const loadAllOrders = async (exchange, dispatch) => {
// Fetch cancelled orders with the "Cancel" event stream
const fromBlock = 0;
const toBlock = "latest";
const cancelFilter = exchange.filters.CancelOrder();
const cancelStream = await exchange.queryFilter(cancelFilter, fromBlock, toBlock);
console.log(cancelStream)
// Format cancelled orders
const cancelledOrders = cancelStream.map((event) => event.args);
// Add cancelled orders to the redux store
dispatch(cancelledOrdersLoaded(cancelledOrders));
}
from my actions:
export const cancelledOrdersLoaded = (cancelledOrders) => {
return {
type: 'CANCELLED_ORDERS_LOADED',
payload:cancelledOrders
}
}
from my reducers:
export const exchange = (state = initialState, action) => {
switch (action.type) {
case 'EXCHANGE_LOADED':
return { ...state, loaded:true, contract: action.payload }
case 'CANCELLED_ORDERS_LOADED':
return { ...state, cancelledOrders: action.payload }
default:
return state
}
my configureStore
// For redux dev tools
const devTools = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
const store = createStore(
rootReducer,
compose(applyMiddleware(thunk),devTools)
)
Thanks in advance
I haven't worked with redux for quite some time now, but from a quick look at some of my older repos, it seems like you didn't set up your store correctly.
This is what I have there,
import { applyMiddleware, createStore, compose, combineReducers } from "redux"
import thunk from "redux-thunk"
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const rootReducer = combineReducers({
reducers...
})
export const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)))
'use strict'
const functions = require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification=functions.database.ref('/notifications/{user_id}/{notification_id }').onWrite((change,context) =>{
const user_id=context.params.user_id;
const notification_id=context.params.notification_id;
console.log('The user ID is :',user_id);
if(!change.after.val()){
return console.log('A notification has been deleted from database:',notification_id);
}
const fromUser=admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult=>{
const from_user_id=fromUserResult.val().from;
console.log('You have new notification from: : ', from_user_id);
const userQuery=admin.database().ref(`users/${from_user_id}/name`).once('value');
return userQuery.then(userResult=>{
const userName=userResult.val();
const deviceToken=admin.database().ref(`/users/${user_id}/device_token`).once('value');
return deviceToken.then(result =>{
const token_id=result.val();
const payload={
notification:{
title:"Friend Request",
body:`${userName} has sent you request`,
icon:"default"
}
};
return admin.messaging().sendToDevice(token_id, payload);
});
});
});
});
TypeError: Cannot read property 'from' of null
at fromUser.then.fromUserResult (/user_code/index.js:22:47)
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
The only line of code where you're accessing a property called from is here:
const from_user_id=fromUserResult.val().from;
Therefore, fromUserResult.val() must be returning null.
fromUserResult is a DataSnapshot type object. According to the API documentation for the val() method, it can return null if there is no data at the location of the query. So, you will have to check for that case in your code.
I have achieved sending a notification with sender's name using this code:
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_user_id = context.params.receiver_user_id;
const notification_id = context.params.notification_id;
if(!data.after.val())
{
console.log('A notification has been deleted :' , notification_id);
return null;
}
const sender_user_id = admin.database().ref(`/Notifications/${receiver_user_id}/${notification_id}`).once('value');
return sender_user_id.then(fromUserResult =>
{
const from_sender_user_id = fromUserResult.val().from;
const userQuery = admin.database().ref(`/Users/${from_sender_user_id}/name`).once('value');
return userQuery.then(userResult =>
{
const senderUserName = userResult.val();
console.log('You have notification from :' , senderUserName);
const DeviceToken = admin.database().ref(`/Users/${receiver_user_id}/device_token`).once('value');
console.log('Checkpoint2');
return DeviceToken.then(result =>
{
const token_id = result.val();
const payload =
{
notification:
{
//from_sender_user_id : from_sender_user_id,
title: "New Chat Request",
body: `${senderUserName} wants to connect with you`,
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response =>
{
console.log('This was the notification Feature');
return null;
}).catch(error => {
console.error(error);
res.error(500);
});
});
});
});
});