TypeError: Cannot read property 'find' of undefined trying to add extra items to Cart
I am trying to add extra items to the Cart using useContext, but the code keeps crashing with the error of "TypeError: Cannot read property 'find' of undefined". I want to add the items in the Cart and I do not know if this code should work, perhaps i am doing something wrong.
This is the CartProvider code:
import { useState } from "react";
import CartContext from "./CartContext";
export const CartProvider = ({ children }) => {
const [list, setList] = useState();
const addCart = (varietals) => {
const isInCart = list.find((x) => x.id === varietals.id);
if (isInCart) {
setList(
list.map((x) =>
x.id === varietals.id ? { ...isInCart, qty: isInCart.qty + 1 } : x
)
);
}else{
setList([...list, { ...varietals, qty: 1 }]);
}
};
return(
<>
<CartContext.Provider value={{list, addCart}}>
{children}
</CartContext.Provider>
</>);
};
Varietals contains all the details of each item.
See also questions close to this topic
-
Firebase Cloud function in expo project
So I have a cloud function (this is not in the react native app directory yet):
const admin = require('firebase-admin'); const firebase_tools = require('firebase-tools'); const functions = require('firebase-functions'); admin.initializeApp(); exports.deleteUser = functions .runWith({ timeoutSeconds: 540, memory: '2GB' }) .https.onCall((data, context) => { const userId = context.auth.uid; var promises = []; // DELETE DATA var paths = ['users/' + userId, 'messages/' + userId, 'chat/' + userId]; paths.forEach((path) => { promises.push( recursiveDelete(path).then( () => { return 'success'; } ).catch( (error) => { console.log('Error deleting user data: ', error); }) ); }); // DELETE FILES const bucket = admin.storage().bucket(); var image_paths = ["avatar/" + userId, "avatar2/" + userId, "avatar3/" + userId]; image_paths.forEach((path) => { promises.push( bucket.file(path).delete().then( () => { return 'success'; } ).catch( (error) => { console.log('Error deleting user data: ', error); }) ); }); // DELETE USER promises.push( admin.auth().deleteUser(userId) .then( () => { console.log('Successfully deleted user'); return true; }) .catch((error) => { console.log('Error deleting user:', error); }) ); return Promise.all(promises).then(() => { return true; }).catch(er => { console.error('...', er); }); }); function recursiveDelete(path, context) { return firebase_tools.firestore .delete(path, { project: process.env.GCLOUD_PROJECT, recursive: true, yes: true, token: functions.config().fb.token }) .then(() => { return { path: path } }).catch( (error) => { console.log('error: ', error); return error; }); } // [END recursive_delete_function]
This is used for my swift app. How Can I use this for my react native app built with Expo?
I have installed the following
yarn add @react-native-firebase/functions
I have my firebase.js file set up in the root directory:
import * as firebase from "firebase"; // Your web app's Firebase configuration var firebaseConfig = { apiKey: "test", authDomain: "test", databaseURL: "test", projectId: "test", storageBucket: "test", messagingSenderId: "test", appId: "test" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); export default firebase;
I have a button:
<Text>Delete Account</Text> <View> <Button title="Delete Account" color="#F9578E" accessibilityLabel="Delete Account" /> </View>
Which when clicked signs the user out and runs the above cloud function.
-
Cleaner, better way to pass function callback and state to a child component in React?
Right now I am passing a callback function and the current state to a child component from my Parent component. I just feel like the way I write it is ugly or at least could be prettier. Here is the Parent component where I am passing all that (
parentCallback={[moreReviews, limit]}
in the return):const Reviews: FunctionComponent = () => { const [filter, setFilter] = useState([1, 2, 3, 4, 5]); const [order, setOrder] = useState('date_desc'); const [reviews, setReviews] = useState([]); const [limit, setLimit] = useState(1); let variables = { offset: 0, limit: limit, filter: filter, order: order } const {data: dataReviews, loading: loadingReviews, error: errorReviews} = useQuery(GetReviews, { ssr: false, variables: variables, fetchPolicy: "no-cache" }); useEffect(() => { console.log('action going on deps change'); if (!loadingReviews && !errorReviews && dataReviews) { setReviews(!loadingReviews && !errorReviews && dataReviews ? dataReviews.reviews[0].reviews : []); } }, [dataReviews]); function moreReviews(limit: number) { setLimit(limit); } return reviews.length ? ( <div> <div className={`${styles.netreviews_review_rate_and_stars}`}> <ReviewsSideInfo/> <ReviewsContainer reviews={reviews} parentCallback={[moreReviews, limit]} /> </div> </div> ) : <div/>; }; export default Reviews;
And then in my child component I'm accessing it like so :
<button onClick={() => parentCallback[0](parentCallback[1] + 1)}></button>
That is definitely ugly but its working fine.
Also, and probably more importantly, is a better, more efficient way to do that, from a technical point of view ? Thanks
-
Django load text file into html file using jquery
I want to implement this example code from w3schools.com using Django. The code loads a text file into a html file using the jquery
load()
function. The code looks like this<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("#div1").load("demo_test.txt"); }); }); </script> </head> <body> <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div> <button>Get External Content</button> </body> </html>
My question is now, how do I store my text file such that the load function has access to it in my Django project?
-
How can I use react-spring useTransition to go from left to right or viceversa
I have a Switch and a Router, and whenever the route changes, it goes from left to right, I would like to know if there's a simple way that the animation can go from right to left based on the change of the route. Thanks in advance.
https://codesandbox.io/s/page-transition-with-react-router-and-react-spring-b07jp
I found this example online, and for instance, I would like to know how can it go from right to left when you click profile.
-
Widget build with webpack and external assets
My goal is to build js library with some widgets. This library will be used on many different websites, domains etc...
It will be imported on page like normal
jquery
library and it will be hosted on domain e.g.libhome.com
like this:<script src="https://libhome.com/static/lib.js"></script>
This library is build using webpack. It contains react inside and a lot of assets (css, images, fonts). So in some components I'm using such syntax:
import 'assets/styles.css';
Now the question. Let's focus on one asset type for now:
css
. When I try to import and uselib.js
inindex.html
hosted onlibhome.com
then the above import works as expected. So when mylibhome.com/index.html
file contains this import:<script src="https://libhome.com/static/lib.js"></script>
Then this library that is build by webpack can import
assets/styles.css
and inject it intohtml
page inhead
section. In my public folder there isassets
folder withstyles.css
inside and this file is available on:https://libhome.com/assets/styles.css
.On the other hand if this library will be imported on different page. For example let's assume that:
https://other.com/index.html
want to import this js library like this:<script src="https://libhome.com/static/lib.js"></script>
It is imported without any problems but
assets/styles.css
are not injected into thishtml
page inhead
section and I don't know why. I even don't know how to debug this using Chrome Developer Tools because there is no error in network traffic. There is no request forassets/styles.css
at all.I just want to build library that can be imported on any webpage and this library should be able to load assets from
https://libhome.com
and not from domain that this library is imported to because there is no assets folder at all on page that imports this library. For example google maps widget can be imported from external domain and all assets are also imported from external domain.Can somebody give me some hints how to configure
webpack
so this:import 'assets/styles.css';
Will be working fine even if script is loaded on totally different domain? I'm using webpack 4 project ejected from Create React App. In configuration there is plugin: MiniCssExtractPlugin which extracts css to file
assets/styles.css
. -
‘state’ is not defined no-undef
I use a tutorial to learn React and I got stuck pretty quickly. In the tutorial they use this code:
import React, { Component } from "react"; class Counter extends Component { state = { count: 0, }; render() { return ( <React.Fragment> <span>{this.state.count}</span> <button>Increment</button> </React.Fragment> ); } } export default Counter;
And everything works great.
But in my case, I get this error:
src\components\counter.jsx Line 4:3: ‘state’ is not defined no-undef Search for the keywords to learn more about each error.
After trying everything, I think it's because of the react version (They use an older version).
So my question is how to fix this error, And what has actually changed between the versions that prevents my code from working. Tnx!
-
How do I set individual alerts for each block on a Drag and Drop in React?
Here are the files for the task. I am trying to get an alert to show up for each time an item is dragged and I want each item to have a different message. What is the best way of doing so? I do not want each item once they're dragged over to have the same message. Thank you very much for your time.
Boards.js
import React from "react"; function Boards(props) { const drop = (e) => { e.preventDefault(); { /* will stop anything from erroring */ } const block_id = e.dataTransfer.getData("block_id"); { /* move the cards by the id */ } { /* part of the event & use getData and pass key*/ } const block = document.getElementById(block_id); block.style.display = "block"; { /* we're doing this because we are going to hide the block when we first start dragging it */ } e.target.appendChild(block); { /* we're going to grab this target and we're going to add appendchild to props.children which is going to dorop it into this element */ } }; /* when we drop something on top of something, this function will be called */ { /* main concept of drop: transfer the id between the event and use that to get get the element by id and then append it to the board */ } const dragOver = (e) => { e.preventDefault(); { /* when you let go, you can still continue onto the function of dropping; doesn't break */ } }; return ( <div id={props.id} className={props.className} onDrop={drop} onDragOver={dragOver} > {props.children} {/* be able to say <Board>children</Board> */} </div> ); } export default Boards;
Block.js
import React from "react"; function Block(props) { const dragStart = (e) => { const target = e.target; e.dataTransfer.setData("block_id", target.id); { /* set data because that is how we reference that data here we're recieving the elements for the block and as well as the id through target.id*/ } setTimeout(() => { target.style.display = "none"; { /* what this does is allows us to have a reference to it, drag it and then make it invisible and not invisible immediately after dragging */ } }, 0); { /* 0 gives a delay */ } { /* we're setting timeout to zero because it gives it a bit of a delay */ } }; const dragOver = (e) => { if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); { /* stops anything from being called so you can't drag and drop blocks into blocks*/ } }; return ( <div id={props.id} className={props.className} draggable={props.draggable} onDragStart={dragStart} onDragOver={dragOver} > {props.children} </div> ); } export default Block;
Step4.js
import React, { useState } from "react"; // import '../../App.css' import Footer from "../Footer"; import "./Step4.css"; import Boards from "../Boards"; import Block from "../Block"; import "./DragandDrop.css"; import { useHistory } from "react-router-dom"; import Swal from "sweetalert2"; function opensweetalert() { Swal.fire({ title: "Success!", text: "You have chosen the correct luggage. Now you are ready for takeoff!", type: "success" }); } //Button Click Function function opensweetalertdanger() { Swal.fire({ title: "Therichpost", text: "OOPS", type: "warning" }); } function Step4() { const history = useHistory(); function goBack() { history.push("/step3"); } function goNext() { history.push("/busconvo"); } return ( <> <div className="biggwrapper"> <div className="smallersection"> <div className="inner-container-step4"> <h1> Choose Luggage </h1> <h3> <center> In this step, you will pack bags for the virtual trip.{" "} </center> <center> Items you feel are necessary to bring on the trip should be dragged into luggage box and the items that aren't necessary should be left at home. </center>{" "} </h3> <div className="flexbox"> <Boards id="boards-1" className="board"> <Block id="block-1" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-2" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-3" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-4" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-5" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-6" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-7" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-8" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-9" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-10" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-11" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-12" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-13" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> <Block id="block-14" className="block" draggable="true"> {/* <p> Card one </p> */} </Block> </Boards> <Boards id="boards-2" className="board"> {/* <Block id="block-1" className="block" draggable="true"> <p> Card one </p> </Block> */} </Boards> </div> <div className="submitMessage"> <div className="vtMessage"> <button type="submit" className="signupbtn" onClick={opensweetalert} > Submit </button> </div> </div> <button className="goBack" type="submit" onClick={goBack}> Go Back </button> <button className="next" id="next" type="submit" onClick={goNext}> Next </button> </div> </div> </div> <Footer /> </> ); } export default Step4;
-
How to use <img src="./"> in React with Webpack?
I need to create an array of div (with the image inside).
let slides = sliderData.map(() => { let advantagesList = advantages.map((adv) => { return( <li key={adv.id}> {adv.name} </li> ); }); return ( <div key={id}> <span>{name}</span> <ul> {advantagesList} </ul> <img data-src src="./img/1.jpg" alt={alt} /> </div> ); });
My images are in the same folder as the component. How can I insert the correct src to make the webpack work properly? (without "import" because the path to the image will come from the server and the slide is formed by map)
Maybe i need to use "html-loader" in my webpack.config.js, but i don't know how.. I try but it doesn't work.
// Loading HTML { test: /\.html$/, loader: "html-loader", options: { sources: { list: [ { tag: 'img', attribute: "data-src", type: "src" } ] } } }
-
How the React Context API detects changes and re-renders consumers?
I need to understand that how the consumers of a particular provider knows that the value has been changed and the consumers need re-rendering? The documentation says that the algorithm detects the value changes using
Object.is()
and I do not quite understand why we ever need to detect changes in the consumers, since the ONLY way we can change the context value is updating the state in the parent component, which always triggers re-renders in every child components of the parent component?Or the consumers check for changed values because is there any mechanism to provide the changed value to the consumers without using the state in the parent component at all?
class App extends Component { state = { userState: { userName: "yasmikash", userId: "u8662", signedIn: true, }, }; handleOnChange = () => { this.setState({ userState: { ...this.state.userState, signedIn: !this.state.userState.signedIn, }, }); }; render() { return ( <> <h1>App</h1> <button onClick={this.handleOnChange}>Toggle Signed In</button> <AuthContext.Provider value={this.state.userState}> {/* <Component1 > */} {/* <Component2 > */} <Profile /> {/* </Component2> */} {/* </Component1 > */} </AuthContext.Provider> </> ); } }
-
Need react context to update before redirect
I have a
UserContext
that is set whenApp
renders.App
retrieves the current user from a server, and then sets the user context in a provider.So whenever I navigating to a link,
App
renders, get's the current user from the server, and sets it. This allows all the children have access to the user.Problem with
<Redirect>
But I'm running into a problem when I use
<Redirect>
.If the user updates on the server, then
App
needs to re-render in order to get the updated user object.But on a redirect
App
doesn't re-render which leads to an outdated user context until the user refreshes the page in order to re-renderApp
.Example: Login to see your profile
In my code below I have a login button. When the user logs in the page redirects to their profile.
But even though the user is successfully logged in on the server, the user context hasn't updated. This is because redirect doesn't re-render
App
.Is there a way to get redirect to re-render app or some other solution?
Code
The relevant code is below.
The full code is available on the repo here. Download, run
npm i
,npm start
, and then either select and playCompounded Server/React
in the debugger or runnode currentUserServer/server.js
to start the server without the debugger tools.Frontend
App.js
import React, { useEffect, useContext, useState } from "react"; import { UserContext } from "./contexts/UserContext"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import Login from "./Login"; import Profile from "./Profile"; const currentUser = async () => { const user = await fetch("/users/current", {}).then(async (res) => { const userJson = await res.json(); return userJson; }); return user; }; export default function App() { const [user, setUser] = useState(null); useEffect(() => { currentUser().then((user) => { setUser(user); }); }, []); return ( <Router> <div className="App"> <UserContext.Provider value={user}> <Switch> <Route path="/profile"> <Profile /> </Route> <Route path="/"> <Login /> </Route> </Switch> </UserContext.Provider> </div> </Router> ); }
Login.js
import React, { useContext, useState } from "react"; import { Redirect } from "react-router-dom"; import { UserContext } from "./contexts/UserContext"; export default function Login() { const [next, setNext] = useState(false); const currentUser = useContext(UserContext); return ( <div> Logged In:{" "} {!currentUser || currentUser.message === "not logged in" ? "No One" : currentUser.username}{" "} <br></br> <button onClick={() => { fetch("/login", { method: "POST" }).then((res) => { if (res.status === 201) setNext(true); }); }} > Login </button> <button onClick={() => { fetch("/logout", { method: "DELETE" }); }} > Logout </button> {next && <Redirect to="/profile" />} </div> ); }
Profile.js
import React, { useContext } from "react"; import { UserContext } from "./contexts/UserContext"; export default function Profile() { const currentUser = useContext(UserContext); return ( <div> {currentUser && !currentUser.message ? "You're logged in and can edit your profile." : "You're not logged in."} </div> ); }
-
index.js:1 Warning: A context consumer was rendered with multiple children
I simply try to use react provider but somehow i get this error: index.js:1437 Warning: A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure
index.js:1 Warning: A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it.
function MiveJat() { const consumer = React.useContext(abAnarContext); console.log(consumer); return ( <abAnarContext.Consumer> <div>GOlabi</div> </abAnarContext.Consumer> ); }
-
React useContext is returning undefine
I am just getting started with react useContext and have run into a problem i could not find solution. When the context created is called in another file it returns undefined. I have tried to research multiple answers like this and others but could not find one that fix the error.
I tried to create the CartStatusContext here and set some initial state
cartstatuscontext.jsx
import React, { useState } from "react"; const CartStatusContext = React.createContext(); function CartStatusContextProvider({ children }) { const cartDict = { 'in_session': "false", 'battery-level': '8' // level is 1 to 10 } const [cartstatus, setcartstatus] = useState(cartDict); return ( <CartStatusContext.Provider value={{ cartstatus, setcartstatus }}> {children} </CartStatusContext.Provider> ); } export default CartStatusContextProvider export {CartStatusContext}
I then tried to import and call the context in this file but it's crashing the app and i was able to confirm with a console.log print out that the CartStatusContext is coming out as undefine.
my index.jsx
import CartStatusContextProvider , { CartStatusContext } from "../components/cartstatuscontext" // Electron related imports const electron = window.require('electron'); const { ipcRenderer } = electron; const loadBalancer = window.require('electron-load-balancer'); function MainPage(){ const [cartstatus, setcartstatus] = useContext(CartStatusContext); }
what am I doing wrong and how can I fix the undefine error and get the CartStatusContext value?
-
React Native : undefined is not an object (evaluating '_useContext.width')
I want to create a reusable code for different screen sizes. I'm using createContext API so that I wont get to rewrite the code in different screen. I got this error
null is not an object (evaluating '_useContext.width)
Btw, I'm using the useWindowDimensions() from react native https://reactnative.dev/docs/usewindowdimensions. Here's the code.
theme.js import React, {createContext, useState, useEffect} from 'react'; import {useWindowDimensions} from 'react-native'; export const WindowContext = createContext(); export const DefaultTheme = ({children}) => { const WIDTH = useWindowDimensions().width; const HEIGHT = useWindowDimensions().height; const [width, setWidth] = () => useState(WIDTH); const [height, setHeight] = () => useState(HEIGHT); useEffect(() => { const handleSize = () => setWidth(WIDTH); setHeight(HEIGHT); window.addEventListener('resize', handleSize); return () => window.removeEventListener('resize', handleSize); }, []); return ( <WindowContext.Provider value={{ width: width, height: height, }}> {children} </WindowContext.Provider> ); };
and I want to implement the code on my button component
button.js import React, {useContext} from 'react'; import {WindowContext} from '../../theme'; const Button = ({buttonTitle, textColor, ...rest}) => { const {width} = useContext(WindowContext); return ( <> {width < 376 ? ( <DefaultButton height="50" {...rest}> <ButtonText color={textColor}>{buttonTitle}</ButtonText> </DefaultButton> ) : ( <DefaultButton height="60" {...rest}> <ButtonText color={textColor}>{buttonTitle}</ButtonText> </DefaultButton> )} </> ); }; export default Button;